Traverse hierarchical or graph-like data.
Section: Common Table Expressions
Recursive CTE
sql
sql
WITH RECURSIVE org_tree AS (
SELECT employee_id, manager_id, name, 1 AS depth
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.employee_id, e.manager_id, e.name, ot.depth + 1
FROM employees e
JOIN org_tree ot ON ot.employee_id = e.manager_id
)
SELECT *
FROM org_tree
ORDER BY depth, employee_id;Explanation
Recursive CTEs are powerful for trees, nested categories, and parent-child traversal.
Learn the surrounding workflow
Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.
Related commands
Same sheet · prioritizing Common Table Expressions