select thread_id , thread_headline , thread_posted_at , reply_posted_at , last_reply_id , num_replies from ( SELECT distinct on (t.id) t.id AS thread_id, t.headline AS thread_headline, t.posted_at AS thread_posted_at, r.posted_at AS last_reply_posted_at, r.id AS last_reply_id, (SELECT COUNT(*) FROM replies WHERE thread_id = t.id) AS num_replies FROM threads AS t JOIN replies AS r ON t.id = r.thread_id ORDER BY t.id, last_reply_posted_at limit 10 ) as t order by thread_posted_at desc, last_reply_posted_at