Recursive CTE Tree Traversal

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

SqlData Integrity

Code

snippet
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;