Sub topic 6
Walking an org chart
An org chart is the standard case for a recursive query. Each employee row points to a manager row in the same table, and the depth of the tree is unknown. A plain self-join can follow one level per join. A recursive CTE follows as many levels as exist.
This chapter assumes you know self-joins, WHERE and ORDER BY, and the anchor/recursive structure from earlier chapters. The examples run on PostgreSQL and SQLite. The SQL Server differences are covered later in the tutorial.
The data model: an adjacency list
The usual way to store a hierarchy is an adjacency list. Each row stores a reference to its parent. Here the manager_id column holds the id of the employee's manager, and the top person has NULL.
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
manager_id INTEGER REFERENCES employees (id)
);
INSERT INTO employees (id, name, manager_id) VALUES
(1, 'Ada', NULL),
(2, 'Ben', 1),
(3, 'Chen', 1),
(4, 'Dana', 2),
(5, 'Eli', 2),
(6, 'Fay', 3),
(7, 'Gus', 4);The foreign key stops you from pointing at a manager who does not exist. It does not stop cycles, such as two people managing each other. The cycle-detection chapter covers that case.
Top-down: the whole reporting tree
Starting from the person with no manager, the query below finds everyone who reports to them, directly or indirectly.
WITH RECURSIVE chain AS (
SELECT id, name, manager_id, 0 AS depth
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.id, e.name, e.manager_id, c.depth + 1
FROM employees e
JOIN chain c ON e.manager_id = c.id
)
SELECT id, name, depth
FROM chain
ORDER BY depth, name;The result:
| id | name | depth |
|---|---|---|
| 1 | Ada | 0 |
| 2 | Ben | 1 |
| 3 | Chen | 1 |
| 5 | Eli | 2 |
| 4 | Dana | 2 |
| 6 | Fay | 2 |
| 7 | Gus | 3 |
In ORDER BY depth, name, Dana sorts before Eli, so the real output lists Dana (4) first in depth 2. The table shows the same seven people in the same depth groups.
Reading the join direction
The join condition is the part most people get wrong, so read it carefully:
JOIN chain c ON e.manager_id = c.idc holds people already found. e is a candidate employee. The condition says "this candidate's manager is someone I already found." Each iteration therefore moves one level down. The people found last time are the managers, and their direct reports are the new rows.
Iteration by iteration
The database evaluates the query as a loop, using only the rows from the previous step as input to the next.
| Step | Rows the recursive member sees | Rows it produces |
|---|---|---|
| Anchor | none | Ada |
| 1 | Ada | Ben, Chen |
| 2 | Ben, Chen | Dana, Eli, Fay |
| 3 | Dana, Eli, Fay | Gus |
| 4 | Gus | nothing, so the loop ends |
The recursion ends because Gus manages nobody. No cap is needed. A tree always terminates, since each step moves strictly away from the root. Termination is only guaranteed when the data is truly a tree, which is why the guards from the previous chapter still matter for data you do not control.
Starting somewhere other than the root
The anchor decides where the walk begins. To list one manager's whole organization, change the anchor to select that manager.
WITH RECURSIVE team AS (
SELECT id, name, manager_id, 0 AS depth
FROM employees
WHERE id = 2
UNION ALL
SELECT e.id, e.name, e.manager_id, t.depth + 1
FROM employees e
JOIN team t ON e.manager_id = t.id
)
SELECT id, name, depth
FROM team
ORDER BY depth, name;This returns Ben at depth 0, then Dana and Eli at depth 1, then Gus at depth 2. Here depth is relative to Ben, not to the CEO. If you need the absolute level, compute it in a separate walk or carry it from a parent-first traversal.
To count how many people sit under a manager, wrap the walk and subtract the starting row:
WITH RECURSIVE team AS (
SELECT id FROM employees WHERE id = 2
UNION ALL
SELECT e.id
FROM employees e
JOIN team t ON e.manager_id = t.id
)
SELECT COUNT(*) - 1 AS total_reports
FROM team;For Ben the answer is 3: Dana, Eli, and Gus.
Bottom-up: the chain of command
You can also walk upward. Start with one employee and repeatedly move to their manager. The only change is the join direction.
WITH RECURSIVE bosses AS (
SELECT id, name, manager_id, 0 AS steps_up
FROM employees
WHERE id = 7
UNION ALL
SELECT m.id, m.name, m.manager_id, b.steps_up + 1
FROM employees m
JOIN bosses b ON m.id = b.manager_id
)
SELECT id, name, steps_up
FROM bosses
ORDER BY steps_up;The result is Gus (0), Dana (1), Ben (2), Ada (3). The condition m.id = b.manager_id reads "the candidate is the manager of someone already found." When the walk reaches Ada, b.manager_id is NULL. A comparison with NULL is never true, so the join finds nothing and the recursion stops without any extra condition.
| Direction | Anchor | Join condition | Stops when |
|---|---|---|---|
| Down (reports) | The manager | `e.manager_id = c.id` | A row has no reports |
| Up (chain of command) | The employee | `m.id = b.manager_id` | The row's `manager_id` is `NULL` |
Upward walks are cheap, because each iteration produces at most one row. Downward walks can fan out, and the working table grows with the width of each level.
Edge cases to check
Real employee tables rarely match the textbook version. Check these before you trust a result.
- Several roots.
WHERE manager_id IS NULLreturns every row with no manager. With two such rows, the query walks two separate trees. That is correct if it is what you want, but depth values from different trees are then mixed in one result. - Orphans. An employee whose
manager_idpoints to a row that was deleted, or to an ID that was never loaded, is unreachable from anyNULLanchor. They silently vanish from the output. Find them with a left join on the managers:
SELECT e.id, e.name, e.manager_id
FROM employees e
LEFT JOIN employees m ON m.id = e.manager_id
WHERE e.manager_id IS NOT NULL
AND m.id IS NULL;- Self-managing roots. Some systems store the CEO with
manager_id = idinstead ofNULL. TheIS NULLanchor then returns zero rows. If you change the anchor toWHERE manager_id = id, the recursive member also matches the root as its own report, and the query never ends. Exclude it withAND e.id <> e.manager_idin the recursive member. - Type mismatches. The anchor and recursive member must produce compatible column types.
0 AS depthis an integer, andc.depth + 1is an integer, so this is fine. Text columns built by concatenation can fail on engines that fix the type from the anchor, such as SQL Server, where the later chapter on dialects picks this up.
Making the output look like a tree
Sorting by depth, name groups people by level but does not keep each person next to their manager. Getting a true indented tree needs a path column, which the next chapter builds. For now, you can fake indentation with the depth value:
WITH RECURSIVE chain AS (
SELECT id, name, 0 AS depth
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.id, e.name, c.depth + 1
FROM employees e
JOIN chain c ON e.manager_id = c.id
)
SELECT substr(' ', 1, depth * 2) || name AS org_chart
FROM chain
ORDER BY depth, name;This indents each name by two spaces per level. substr and || work in both PostgreSQL and SQLite. Because the rows are still ordered by level and not by branch, Fay appears among Ben's reports in the output. Treat this as a readable listing, not a drawn tree.
Performance note
Each iteration looks up the employees whose manager_id equals one of the current rows. Without an index on manager_id, that lookup scans the whole table once per iteration. Add one:
CREATE INDEX idx_employees_manager ON employees (manager_id);The upward walk looks up by id, which the primary key already covers.
Exercise
Using the employees table from this chapter, write a recursive query that lists every person who reports to Chen, directly or indirectly, without including Chen. Which names should it return?
Show answer
Start the anchor at Chen's direct reports instead of at Chen, so Chen never enters the result. WITH RECURSIVE underchen AS ( SELECT id, name, managerid FROM employees WHERE managerid = 3 UNION ALL SELECT e.id, e.name, e.managerid FROM employees e JOIN underchen u ON e.managerid = u.id ) SELECT id, name FROM under_chen; It returns one name, Fay, because Chen has a single report and Fay has none. An alternative is to anchor at id = 3 and filter WHERE id <> 3 in the final SELECT.
Exercise
In the bottom-up query for Gus, what condition ends the recursion, and why is no WHERE clause needed in the recursive member?
Show answer
After the walk reaches Ada, her managerid is NULL. The join condition m.id = b.managerid compares against NULL, which is never true, so no row matches, the recursive member returns no rows, and the loop ends. Every employee has at most one manager, so each iteration produces at most one row and the chain is finite in a valid hierarchy.