Sub topic 3
Walking an Organization Chart or Category Tree
This chapter assumes you know JOINs, GROUP BY, and basic CTE syntax. It also assumes you can read a query plan at a high level.
A hierarchy stores each row with a pointer to its parent, such as manager_id in an employees table or parent_id in a categories table. A recursive CTE walks such a tree one level per pass:
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 anchor member runs once. The recursive member then joins to the rows found in the previous pass. The engine repeats this until a pass adds no rows.
WITH RECURSIVE versus WITH: differences across databases
PostgreSQL, MySQL 8.0 and later, and SQLite require the RECURSIVE keyword. SQL Server and Oracle do not use it. Check your engine's documentation before you copy a query.
| Database | Requires RECURSIVE keyword |
|---|---|
| PostgreSQL | Yes |
| MySQL 8.0+ | Yes |
| SQLite | Yes |
| SQL Server | No |
How engines execute CTEs: materialized or inlined
Some engines compute a CTE once and store its rows. Others substitute the CTE's query into each place it is used. PostgreSQL 12 and later inline a CTE that is referenced once and has no side effects. The MATERIALIZED keyword forces it to be computed once:
WITH recent AS MATERIALIZED (
SELECT * FROM orders WHERE order_date >= DATE '2026-01-01'
)
SELECT COUNT(*) FROM recent;Data-modifying CTEs (PostgreSQL)
In PostgreSQL, a CTE can contain INSERT, UPDATE, or DELETE. The RETURNING clause passes the affected rows to the outer statement:
WITH moved AS (
DELETE FROM orders
WHERE order_date < DATE '2020-01-01'
RETURNING *
)
INSERT INTO orders_archive
SELECT * FROM moved;Common mistakes and when not to use a CTE
- Omitting
UNION ALLor the termination condition, which causes endless recursion. - Assuming a CTE is always computed once. Check the plan before you rely on it.
- Using a CTE for data that several statements need. A view or temporary table fits better.
Exercise
Using the employees table above, how would you limit the recursion to depth 3?
Show answer
Add WHERE o.depth < 3 to the recursive member, so it stops adding rows after depth 3.