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 thread_posted_at DESC, last_reply_posted_at DESC LIMIT 10