Skip to content

Instantly share code, notes, and snippets.

@robertsosinski
Created June 29, 2012 18:07
Show Gist options
  • Save robertsosinski/3019694 to your computer and use it in GitHub Desktop.
Save robertsosinski/3019694 to your computer and use it in GitHub Desktop.
Recursive querys in PostgresSQL
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;
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;
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;
@toddsundsted
Copy link

slick!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment