Skip to content

Instantly share code, notes, and snippets.

@carymrobbins
Created November 24, 2014 23:14
Show Gist options
  • Save carymrobbins/4b07fa0485b57367d750 to your computer and use it in GitHub Desktop.
Save carymrobbins/4b07fa0485b57367d750 to your computer and use it in GitHub Desktop.
Recursive SQL query to find all nodes in a tree beyond a certain depth. This is for PostgreSQL specifically; however, other RDBMS that support recursive CTEs (e.g. Oracle, SQL Server) should be able to do this as well with a slight modification to the syntax.
with recursive base as (
select * from categories_category
), tree as (
select id, parent_id, 1 as level, name :: text
from base as root
where parent_id is null
union all
select child.id, child.parent_id, parent.level + 1, (parent.name || ' > ' || child.name) :: text
from tree as parent
join base as child
on (parent.id = child.parent_id)
)
select name
from tree
where level > 4;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment