A better approach
WITH RECURSIVE comment_tree (comment_id, level, path) AS ( SELECT comment_id, 0, array[-score, comment_id] FROM comment WHERE thread_id = 2 AND parent_comment_id IS NULL UNION SELECT c.comment_id, level + 1, ct.path || -c.score || c.comment_id FROM comment c, comment_tree ct WHERE c.parent_comment_id = ct.comment_id ) SELECT ct.path, ct.level, c.text FROM comment_tree ct JOIN comment c USING (comment_id) ORDER BY 1;