Created
November 24, 2014 23:14
-
-
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.
This file contains hidden or 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 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