Recursive CTE Tree Traversal

Traverse hierarchical trees with recursive CTEs for org chart and category navigation.

SqlData Integrity

Code

sqlsnippet
12 lines
WITH RECURSIVE org_tree AS (
  SELECT id, name, parent_id, 0 AS depth, name::text AS path
  FROM departments
  WHERE parent_id IS NULL
  UNION ALL
  SELECT d.id, d.name, d.parent_id, ot.depth + 1, ot.path || ' > ' || d.name
  FROM departments d
  JOIN org_tree ot ON d.parent_id = ot.id
)
SELECT id, name, depth, path
FROM org_tree
ORDER BY path;

What the code does

What runs is SELECT, with departments and org_tree as the object involved.

The SQL constructs in play: a CTE (WITH … AS) that names an intermediate result before the main query; one JOIN combining rows across tables; a WHERE clause that picks out the rows one statement touches; an ORDER BY that fixes the output order; a UNION stacking the result sets of separate queries into one.

Applying it

The departments table is the working surface here.

Interactive Tools for This Topic

FAQ

What objects does the SQL involve?
The references are `departments`, `org_tree`, with one join tying the pair together.