Skip to content

Instantly share code, notes, and snippets.

@fortytw2
Created July 6, 2015 07:57
Show Gist options
  • Save fortytw2/e58d4c28ecbf02eef8bd to your computer and use it in GitHub Desktop.
Save fortytw2/e58d4c28ecbf02eef8bd to your computer and use it in GitHub Desktop.
recursive sql
WITH RECURSIVE cte (id, body, op_id, path, comment_id, depth) AS (
SELECT id,
body,
op_id,
array[id] AS path,
comment_id,
1 AS depth
FROM comments
WHERE comment_id = 0 AND post_id = $1
UNION ALL
SELECT comments.id,
comments.body,
comments.op_id,
cte.path || comments.id,
comments.comment_id,
cte.depth + 1 AS depth
FROM comments
JOIN cte ON comments.comment_id = cte.id
)
SELECT id, body, op_id, comment_id, path, depth FROM cte
ORDER BY path;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment