Sub topic 7
Walking an Organization Chart or Category Tree
This chapter applies recursive CTEs to the most common real-world case: a table in which each row points at its parent. You will walk such a tree top-down, bottom-up, and in display order. You will also guard against bad data.
It assumes you can write a basic recursive CTE (an anchor member, UNION ALL, and a recursive member) and that you are comfortable with self-joins. Examples run on PostgreSQL. Where another database differs, a note says so.
The shape of the data: an adjacency list
Most hierarchies in relational databases are stored as an adjacency list. Each row holds a reference to its parent's key. The root has NULL as its parent.
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, 'Ava', NULL),
(2, 'Ben', 1),
(3, 'Cara', 1),
(4, 'Dev', 2),
(5, 'Elin', 2),
(6, 'Femi', 3),
(7, 'Gus', 4);A plain query can reach one level at a time with a self-join. It cannot reach a depth that is unknown in advance. A recursive CTE can.
Top-down: from the root to everyone below
The anchor member selects the root. The recursive member joins employees to the rows found in the previous round and keeps the employees whose manager_id matches.
WITH RECURSIVE org 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, o.depth + 1
FROM employees e
JOIN org o ON e.manager_id = o.id
)
SELECT id, name, depth
FROM org
ORDER BY depth, name;The result is Ava at depth 0, Ben and Cara at 1, Dev, Elin and Femi at 2, and Gus at 3.
The engine evaluates this in rounds. Each round sees only the rows the previous round produced.
| Round | Rows produced | Why |
|---|---|---|
| Anchor | Ava | `manager_id IS NULL` |
| 1 | Ben, Cara | Their manager is Ava |
| 2 | Dev, Elin, Femi | Their managers are Ben or Cara |
| 3 | Gus | His manager is Dev |
| 4 | none | Nobody reports to Gus, so recursion ends |
In a healthy tree, recursion stops by itself because a leaf has no children. No WHERE limit is needed. A limit becomes necessary only when the data might contain a cycle, covered below.
Carrying a path along
A column that grows by one element per round is the usual way to carry context down the tree. A text breadcrumb is useful for display.
WITH RECURSIVE org AS (
SELECT id, name, 0 AS depth, name AS path
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.id, e.name, o.depth + 1, o.path || ' > ' || e.name
FROM employees e
JOIN org o ON e.manager_id = o.id
)
SELECT repeat(' ', depth) || name AS indented, path
FROM org
ORDER BY depth, name;For Gus, path is Ava > Ben > Dev > Gus.
Starting from any node: subtrees
The anchor does not have to be the root. Change the anchor and you get the subtree under any node. This query counts everyone below Ben (id 2):
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 reports
FROM team;The team set contains Ben, Dev, Elin and Gus, so the count is 4. Subtracting 1 removes Ben himself, leaving 3 reports. Keep the anchor row in the set. It is simpler than excluding it and handling the one-row edge case separately.
Bottom-up: the chain of command
To find all ancestors of one row, reverse the join. The anchor is the starting employee. Each round looks up the manager of the previous round's row.
WITH RECURSIVE chain AS (
SELECT id, name, manager_id, 0 AS steps
FROM employees
WHERE name = 'Gus'
UNION ALL
SELECT e.id, e.name, e.manager_id, c.steps + 1
FROM employees e
JOIN chain c ON e.id = c.manager_id
)
SELECT steps, name
FROM chain
ORDER BY steps;The result is Gus (0), Dev (1), Ben (2), Ava (3).
Compare the two join conditions:
| Direction | Join condition | Each round returns |
|---|---|---|
| Down | `e.manager_id = o.id` | Possibly many rows (all children) |
| Up | `e.id = c.manager_id` | At most one row (the single parent) |
An upward walk never fans out, so it stays cheap. It ends when manager_id is NULL, because the join then matches nothing.
Stopping recursion on bad data
The trees above terminate because the data is a tree. Real tables are not always trees. Someone sets manager_id to point at a descendant, and an upward walk then loops forever. There are two defenses.
A depth limit is a blunt cap. It guarantees termination but silently truncates legitimate deep trees if the limit is too low.
WITH RECURSIVE org AS (
SELECT id, name, 0 AS depth
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.id, e.name, o.depth + 1
FROM employees e
JOIN org o ON e.manager_id = o.id
WHERE o.depth < 20
)
SELECT id, name, depth FROM org;A visited-path guard detects the actual cycle. It records the ids seen so far on each branch and refuses to step onto one of them.
WITH RECURSIVE chain AS (
SELECT id, manager_id, ARRAY[id] AS seen
FROM employees
WHERE id = 7
UNION ALL
SELECT e.id, e.manager_id, c.seen || e.id
FROM employees e
JOIN chain c ON e.id = c.manager_id
WHERE e.id <> ALL (c.seen)
)
SELECT id, seen FROM chain;On clean data this returns Gus, Dev, Ben, Ava, with seen growing from {7} to {7,4,2,1}. On cyclic data the walk stops at the first repeated id. The array makes each row larger as the walk deepens. This is fine for ordinary hierarchies and costly for very deep ones.
Display order for a category tree
Sorting by depth groups levels together, which is wrong for a menu or an indented listing. You want depth-first order: a parent, then all of its descendants, then its next sibling. Carry an array of sort keys from the root down and sort on it.
CREATE TABLE categories (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
parent_id INTEGER REFERENCES categories (id),
sort_order INTEGER NOT NULL DEFAULT 0
);
INSERT INTO categories (id, name, parent_id, sort_order) VALUES
(1, 'Electronics', NULL, 1),
(2, 'Home', NULL, 2),
(3, 'Phones', 1, 1),
(4, 'Laptops', 1, 2),
(5, 'Accessories', 3, 1),
(6, 'Kitchen', 2, 1);
WITH RECURSIVE tree AS (
SELECT id, name, 0 AS depth,
ARRAY[sort_order] AS sort_path,
name AS crumb
FROM categories
WHERE parent_id IS NULL
UNION ALL
SELECT c.id, c.name, t.depth + 1,
t.sort_path || c.sort_order,
t.crumb || ' / ' || c.name
FROM categories c
JOIN tree t ON c.parent_id = t.id
)
SELECT repeat(' ', depth) || name AS label, crumb
FROM tree
ORDER BY sort_path;PostgreSQL compares arrays element by element, so {1} sorts before {1,1}, which sorts before {1,1,1} and {1,2}. The output reads:
Electronics
Phones
Accessories
Laptops
Home
KitchenThis assumes sort_order is unique among siblings. If two siblings tie, their subtrees interleave. Append a tiebreaker such as the id to each element, or enforce uniqueness with a constraint on (parent_id, sort_order).
Dialect and performance notes
- Index the parent column (
manager_id,parent_id). The recursive member joins on it once per round, so without an index each round scans the table. - The recursive member can reference the CTE only once in most engines, and aggregates or
DISTINCTinside it are restricted. Put aggregation in the outer query, as the subtree count does. - If you walk the same hierarchy on every request and it rarely changes, consider storing a materialized path or a closure table instead. Recursive CTEs are best when hierarchies are modest in size or queried occasionally.
Common mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| Query never finishes or hits a recursion limit | Cycle in the data | Add a path guard, `CYCLE`, or a depth cap |
| Empty result | Anchor filter matches nothing (for example, the root has `0`, not `NULL`, as parent) | Check the anchor on its own first |
| Rows appear twice | A node has two parents in the data, or `UNION` was misused | Fix the data, or confirm the table is truly a tree |
| Type mismatch error | Anchor and recursive columns differ in type | Cast in the anchor |
| Menu order is wrong | Sorted by `depth` instead of a path | Sort by the accumulated sort-key array |
| Walk goes the wrong way | Join condition reversed | Down: `child.parent = prev.id`. Up: `parent.id = prev.parent` |
Exercise
Using the employees table, write the idea for a query that returns how many managers sit above Femi. Which direction does the join go, and what is the answer?
Show answer
Walk upward. Anchor on WHERE name = 'Femi', and make the recursive member join with e.id = c.manager_id, incrementing a steps counter. The chain is Femi (0), Cara (1), Ava (2). So there are 2 managers above Femi, which is the maximum steps value.
Exercise
In the top-down org query, someone updates Ava's row so that manager_id = 7 instead of NULL. What does the query return, and does it loop forever?
Show answer
It returns no rows and terminates. The anchor selects rows where manager_id IS NULL, and now no row matches, so the recursive member never has input to work with. An infinite loop would occur only in a walk that can reach the cycle, such as the upward walk starting from Gus, which would now go Gus, Dev, Ben, Ava, Gus and so on. That walk needs a visited-path guard, CYCLE, or a depth limit.