Created
June 29, 2012 18:07
-
-
Save robertsosinski/3019694 to your computer and use it in GitHub Desktop.
Recursive querys in PostgresSQL
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
with recursive category_ancestors (id, parent_id, name) as ( | |
select id, parent_id, name | |
from categories where id = 123 | |
union | |
select parent.id, parent.parent_id, parent.name | |
from categories parent | |
inner join category_ancestors on parent.id = category_ancestors.parent_id | |
) | |
select * from category_ancestors; |
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
with recursive category_graph as ( | |
select id, parent_id, name | |
from categories where id = 1 | |
union | |
select child.id, child.parent_id, child.name | |
from category_graph | |
inner join categories as child on child.parent_id = category_graph.id | |
) | |
select * from category_graph; |
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
with recursive category_graph as ( | |
select id, parent_id, name, array[id] as path, 1 as depth | |
from categories where id = 1 | |
union | |
select child.id, child.parent_id, child.name, array_append(category_graph.path, child.id) as path, category_graph.depth + 1 as depth | |
from category_graph | |
inner join categories as child on child.parent_id = category_graph.id | |
) | |
select * from category_graph order by path; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
slick!