Recursive CTEs, Hierarchies and Number Series
Use recursive common table expressions to walk hierarchies such as org charts and category trees, build number and date series without a calendar table, and avoid runaway recursion.
- Explain the anchor member, the recursive member and the stopping condition of a recursive CTE
- Walk an org chart or category tree and report each node's level and full path
- Generate number and date series inside SQL
- Protect queries against infinite recursion
Why hierarchies need recursion
Many business tables describe a tree. An employee reports to a manager who reports to a director. A product category contains sub-categories, which contain products. A bill of materials lists parts that are themselves made of parts. A plain JOIN only goes one level deep. A recursive CTE keeps joining a table to its own results until no new rows appear, so it can walk any depth.
A regional head wants to know, for every employee, how many management levels sit above them and who their top-level leader is, so that a re-organisation can be planned. The org chart is a single table where each row names its manager. One query has to follow that chain to the top, whatever its length.
Anatomy of a recursive CTE
Every recursive CTE has three parts:
- Anchor member: the starting rows, for example the people with no manager.
- Recursive member: a query that joins back to the CTE itself to find the next level.
- Stopping condition: the recursion ends when the recursive member returns no rows.
WITH RECURSIVE name AS (
SELECT ... -- anchor: level 0
UNION ALL
SELECT ... -- recursive: joins name to the next level
FROM table t
JOIN name n ON ...
)
SELECT * FROM name;UNION ALL is the usual choice, because it does not remove duplicates and so runs faster. Use UNION only when you need the engine to drop repeated rows, which also protects against cycles (see the warning below). In SQL Server the keyword RECURSIVE is not written; in PostgreSQL, DuckDB and SQLite it is.
Example 1: an org chart
The table below is self-contained so you can run it as written. Each person has at most one manager; the CEO has no manager.
WITH RECURSIVE org(emp_id, name, manager_id) AS (
VALUES
(1, 'Anika', NULL),
(2, 'Rohit', 1),
(3, 'Meera', 1),
(4, 'Kabir', 2),
(5, 'Tara', 2),
(6, 'Dev', 3),
(7, 'Isha', 4)
),
chain AS (
-- Anchor: the top of the hierarchy
SELECT emp_id, name, manager_id, 0 AS level, name AS path
FROM org
WHERE manager_id IS NULL
UNION ALL
-- Recursive: everyone whose manager is already in the chain
SELECT o.emp_id, o.name, o.manager_id, c.level + 1, c.path || ' > ' || o.name
FROM org o
JOIN chain c ON o.manager_id = c.emp_id
)
SELECT level, name, path
FROM chain
ORDER BY path;| level | name | path |
|---|---|---|
| 0 | Anika | Anika |
| 1 | Meera | Anika > Meera |
| 2 | Dev | Anika > Meera > Dev |
| 1 | Rohit | Anika > Rohit |
| 2 | Kabir | Anika > Rohit > Kabir |
| 3 | Isha | Anika > Rohit > Kabir > Isha |
| 2 | Tara | Anika > Rohit > Tara |
Read the result as a tree: level 0 is the CEO, level 1 the direct reports, and so on. The path column is built on the way down by appending each name to the parent's path, which is a common pattern for showing a breadcrumb.
Key idea: the recursive member can use anything the anchor produced, here c.level and c.path. That is how depth and paths are accumulated.
Example 2: team totals across the whole tree
Once you can attach a root and a level to every node, you can roll up numbers. Here every person's team size counts everyone below them.
WITH RECURSIVE org(emp_id, name, manager_id) AS (
VALUES (1,'Anika',NULL),(2,'Rohit',1),(3,'Meera',1),(4,'Kabir',2),(5,'Tara',2),(6,'Dev',3),(7,'Isha',4)
),
below AS (
-- Each person paired with every person who reports to them, at any depth
SELECT manager_id AS boss, emp_id AS report FROM org WHERE manager_id IS NOT NULL
UNION ALL
SELECT b.boss, o.emp_id
FROM below b
JOIN org o ON o.manager_id = b.report
)
SELECT o.name, COUNT(b.report) AS people_below
FROM org o
LEFT JOIN below b ON b.boss = o.emp_id
GROUP BY o.name
ORDER BY people_below DESC, o.name;| name | people_below |
|---|---|
| Anika | 6 |
| Rohit | 3 |
| Kabir | 1 |
| Meera | 1 |
| Dev | 0 |
| Isha | 0 |
| Tara | 0 |