Sub topic 6
Walking an Org Chart with a Recursive CTE
Assume you know SELECT, WHERE, ORDER BY, inner joins, self-joins, GROUP BY, and basic subqueries. This chapter uses PostgreSQL syntax for arrays, but the recursive pattern applies to other SQL databases.
An org chart is a parent-child hierarchy. Each employee has a manager_id that points to another row in the same employees table. A top-level employee has no manager, so manager_id is NULL.
The recursive shape
A recursive common table expression, or recursive CTE, has two parts:
- The anchor member selects the starting rows.
- The recursive member finds the next rows from the rows already found.
The two parts must return the same number of columns with compatible types. UNION ALL combines them while preserving every result row.
For an org chart, the anchor selects the root employees. The recursive member joins employees to the previous level by matching e.manager_id with the current employee's id.
WITH RECURSIVE org AS (
-- Anchor: begin with employees who have no manager.
SELECT
id,
name,
manager_id,
0 AS depth,
ARRAY[id] AS path
FROM employees
WHERE manager_id IS NULL
UNION ALL
-- Recursive member: find direct reports.
SELECT
e.id,
e.name,
e.manager_id,
org.depth + 1,
org.path || e.id
FROM employees AS e
JOIN org
ON e.manager_id = org.id
WHERE org.depth < 10
AND e.id <> ALL (org.path)
)
SELECT
id,
name,
manager_id,
depth,
path
FROM org
ORDER BY path;The depth column counts edges from the root. A CEO has depth 0. A direct report has depth 1. An employee two levels below the CEO has depth 2.
The PostgreSQL path array records the IDs visited so far. For example, {1,4,9} means that employee 9 was reached through employee 4, who was reached through employee 1. Ordering by this array keeps descendants near their manager in the result.
How the database walks the tree
The database evaluates the CTE in iterations:
- It places all root employees in the initial working set.
- It joins the next iteration of
employeesto those roots. - It adds the discovered employees to
org. - It repeats the join using the newly discovered employees.
- It stops when an iteration produces no rows.
The query does not need to know how many levels the organization has. The org.depth < 10 condition adds a safety limit. Remove or adjust it only when the expected maximum depth is known.
The path condition, e.id <> ALL (org.path), prevents a row from being visited twice on the same branch. This matters because bad data can contain a cycle, such as employee 4 managing employee 9 while employee 9 eventually manages employee 4. Without a depth limit or cycle check, the query might continue indefinitely or hit the database's recursion limit.
Choosing the starting point
To show the entire company, keep the anchor condition manager_id IS NULL. To show only one manager's reporting tree, anchor on that employee instead:
WITH RECURSIVE reports AS (
SELECT id, name, manager_id, 0 AS depth
FROM employees
WHERE id = 7
UNION ALL
SELECT e.id, e.name, e.manager_id, reports.depth + 1
FROM employees AS e
JOIN reports
ON e.manager_id = reports.id
WHERE reports.depth < 10
)
SELECT id, name, depth
FROM reports
ORDER BY depth, name;This version includes employee 7 as the root. It then returns direct reports, their reports, and so on.
Exercise
How would you change the second query to exclude employee 7 and return only that employee's descendants?
Show answer
Keep employee 7 in the anchor so the recursive member can find its children, then add WHERE depth > 0 to the outer query, or wrap the CTE and filter depth > 0 there.