A first attempt at sorting
WITH RECURSIVE comment_tree (comment_id, sort_key) AS ( SELECT comment_id, to_char(score, '0000') FROM comment WHERE thread_id = 2 AND parent_comment_id IS NULL UNION SELECT c.comment_id, ct.sort_key || to_char(score, '0000') FROM comment c, comment_tree ct WHERE c.parent_comment_id = ct.comment_id ) SELECT ct.sort_key || 'Z' as zort_key, c.text FROM comment_tree ct JOIN comment c USING (comment_id) ORDER BY 1 DESC;