Recursive CTE: Employee Hierarchy
Walk the manager tree recursively to list each employee and their management chain depth.
Overview
Recursive CTEs shine for hierarchical data stored with parent pointers — like
employees.manager_id. We start from top-level managers (manager_id IS NULL)
and recursively join to their reports, tracking depth. This is the canonical
"org chart" query.
The Query
Employees & Departments
Loading database engine...
Step-by-Step Breakdown
- Anchor:
WHERE manager_id IS NULLselects the top-level managers. - Recursive step: joins
employeesto the growingorgCTE onmanager_id = org.id, adding one level of reports each pass. depthincrements per level, showing how far down the tree each person sits.
Cycles will hang
A cyclic manager_id chain (A manages B manages A) causes infinite recursion.
Real schemas enforce acyclic trees.
Variations
Show the management path as a concatenated string:
Employees & Departments
Loading database engine...
Common Mistakes
- Missing anchor filter. Without
WHERE manager_id IS NULLthe recursion has no defined starting point. - Cycles. Self-referential manager loops cause runaway recursion.
- Wrong join direction. Joining
org.id = e.idinstead ofe.manager_id = o.idwon't walk down the tree.