Created
January 7, 2021 12:49
-
-
Save mauricioszabo/e2d26a617f68787b4081c8e62559ce18 to your computer and use it in GitHub Desktop.
PostgreSQL example of recursive queries
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
INSERT INTO tree (id, parent_id, description) | |
VALUES | |
(6, 6, 'Im Recursive'); | |
WITH RECURSIVE parents as ( | |
select id, | |
description, | |
parent_id | |
from tree | |
where parent_id = 6 | |
union all | |
select child.id, | |
child.description, | |
child.parent_id | |
from tree as child | |
join parents on parents.id = child.parent_id | |
) | |
select * from parents; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE TABLE tree( | |
id SERIAL PRIMARY KEY, | |
parent_id INTEGER, | |
description VARCHAR | |
); | |
INSERT INTO tree (id, parent_id, description) | |
VALUES | |
(1, null, 'level 0'), | |
(2, 1, 'level 1'), | |
(3, 2, 'level 2'), | |
(4, null, 'Another level 0'), | |
(5, 4, 'Another level 1'); | |
WITH RECURSIVE parents as ( | |
select id, | |
description, | |
parent_id | |
from tree | |
where parent_id IS NULL | |
union all | |
select child.id, | |
child.description, | |
child.parent_id | |
from tree as child | |
join parents on parents.id = child.parent_id | |
) | |
select * from parents; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment