Recursive CTE: trees and hierarchies
You need it when a table points to itself: categories with a parent, employees with a manager, parts made of other parts. A self-join goes down one level; a recursive CTE goes down as many levels as there are.
WITH RECURSIVE tree AS (
SELECT category_id, name, 1 AS depth
FROM categories
WHERE parent_category_id IS NULL
UNION ALL
SELECT c.category_id, c.name, t.depth + 1
FROM categories c
JOIN tree t ON c.parent_category_id = t.category_id
)
SELECT * FROM tree;
The anchor (the first SELECT) runs once and gives the top categories. The recursive member reads tree itself: each
round, it finds the children of the rows the previous round added, and the recursion stops when a round adds none.
The trap. A loop in the data (an employee who is, through others, their own manager) and the query never ends, or
stops at an engine limit after a long wait. Give the recursive member a guard: a maximum depth (WHERE t.depth < 20),
or the path so far, refusing a node already on it.
On your warehouse. Postgres and BigQuery require the word RECURSIVE; Snowflake accepts it but does not need it.
Databricks runs recursive CTEs only on recent runtimes (since 2025). On Postgres, cast a text column that grows in the
recursion in the anchor (CAST(name AS TEXT)): otherwise its type differs between the two halves, and the query fails.
WITH RECURSIVE tree AS ( SELECT category_id, name, 1 AS depth, CAST(name AS VARCHAR) AS path FROM categories WHERE name = 'Drinks' UNION ALL SELECT c.category_id, c.name, t.depth + 1, t.path || ' > ' || c.name FROM categories c JOIN tree t ON c.parent_category_id = t.category_id ) SELECT category_id, depth, path FROM tree ORDER BY path;
| category_id | depth | path |
|---|---|---|
| 14 | 1 | Drinks |
| 1 | 2 | Drinks > Coffee |
| 6 | 3 | Drinks > Coffee > Capsules |
| 4 | 3 | Drinks > Coffee > Coffee beans |
| 5 | 3 | Drinks > Coffee > Ground coffee |
| 2 | 2 | Drinks > Tea |
| 8 | 3 | Drinks > Tea > Black tea |
| 7 | 3 | Drinks > Tea > Green tea |
| 9 | 3 | Drinks > Tea > Herbal teas |