Skip to content

Instantly share code, notes, and snippets.

@adriaandotcom
Last active November 19, 2018 08:00
Show Gist options
  • Save adriaandotcom/ca1e6c730418362d7448056202e32be8 to your computer and use it in GitHub Desktop.
Save adriaandotcom/ca1e6c730418362d7448056202e32be8 to your computer and use it in GitHub Desktop.
Output of teppic's answer
CREATE TABLE IF NOT EXISTS comment (
comment_id serial primary key,
original_id integer,
text text,
upvotes integer
);
INSERT INTO "public"."comment" ("comment_id", "original_id", "text", "upvotes") VALUES
('1', NULL, 'Hi.. should be 1', '10'),
('2', NULL, 'Je.. should be 10', '0'),
('3', '1', 'Di.. should be 6', '0'),
('4', '1', 'Si.. should be 2', '7'),
('5', '1', 'Op.. should be 3', '5'),
('6', NULL, 'Op.. should be 8', '2'),
('7', '6', 'Op.. should be 9', '2'),
('8', '5', 'Op.. should be 4', '8'),
('9', '1', 'Op.. should be 5', '3'),
('10', '1', 'Th.. should be 7', '0');
comment_id original_id upvotes text depth path
1 10 Hi.. 0 {1}
3 1 0 Di.. 1 {1,3}
4 1 7 Si.. 1 {1,4}
5 1 5 Op.. 1 {1,5}
8 5 8 Op.. 2 {1,5,8}
9 1 3 Op.. 1 {1,9}
10 1 0 Th.. 1 {1,10}
2 0 Je.. 0 {2}
6 2 Op.. 0 {6}
7 6 2 Op.. 1 {6,7}
WITH RECURSIVE comment_tree AS (
-- First select performed to get top level rows
SELECT
comment_id,
original_id,
upvotes,
text,
0 depth, -- depth in the tree
ARRAY [comment_id] path -- path to node (used to sort depth-first)
FROM
comment
WHERE
original_id IS NULL
UNION
-- Self referential select performed repeatedly until no more rows are found
SELECT
c.comment_id,
c.original_id,
c.upvotes,
c.text,
ct.depth + 1,
ct.path || c.comment_id
FROM
comment c
JOIN comment_tree ct ON c.original_id = ct.comment_id
)
SELECT
*
FROM
comment_tree
ORDER BY
path
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment