Skip to content

Instantly share code, notes, and snippets.

@rsaryev
Last active April 5, 2022 23:08
Show Gist options
  • Save rsaryev/38ef0192a94bc37462f4778ab5ac5723 to your computer and use it in GitHub Desktop.
Save rsaryev/38ef0192a94bc37462f4778ab5ac5723 to your computer and use it in GitHub Desktop.
WITH RECURSIVE tree AS (SELECT *, id AS root_category
FROM categories
WHERE parentId IS NULL
UNION ALL
SELECT c.*, p.root_category
FROM categories c
JOIN tree p
ON c.parentId = p.id)
SELECT *
FROM tree
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment