Recursive CTEs: Trees & Hierarchies
Structure
WITH RECURSIVE tree AS (
-- 1. Anchor: the starting rows
SELECT … FROM t WHERE parent_id IS NULL
UNION ALL
-- 2. Recursive part: join the table to the rows found so far
SELECT … FROM t JOIN tree ON t.parent_id = tree.id
)
SELECT * FROM tree;
How it runs
- Run the anchor → the first set of rows
- Run the recursive part using only the rows from the previous step
- Repeat step 2 until it returns no new rows
- All rows combined = the result
Useful extra columns
depth/level– add 1 each step:tree.depth + 1path– build a breadcrumb:tree.path || ' > ' || t.name, or an arraytree.path || t.id- Use
pathto sort the tree in display order
Common uses
- Category / folder trees (all sub-categories under "Food")
- Referral chains: who referred whom, at any depth
- Employee → manager chains (org charts)
- Threaded comments and replies
- Bill-of-materials (parts within parts)
- Generating sequences (numbers, dates) — though
generate_seriesis simpler
⚠️ Avoid infinite loops
If data contains a cycle (A → B → A), recursion never ends.
- Track visited ids in an array and stop:
WHERE NOT t.id = ANY(tree.path) - PostgreSQL 14+: the
CYCLEclause - Add a safety limit:
WHERE depth < 20
UNION (instead of UNION ALL) also removes duplicate rows, which stops some simple cycles.
Example
-- 1. Category tree with depth and breadcrumb path
WITH RECURSIVE tree AS (
SELECT id, name, parent_id, 1 AS depth, name::text AS path
FROM categories
WHERE parent_id IS NULL -- anchor: top-level categories
UNION ALL
SELECT c.id, c.name, c.parent_id, t.depth + 1, t.path || ' > ' || c.name
FROM categories c
JOIN tree t ON c.parent_id = t.id -- recursive step
)
SELECT repeat(' ', depth - 1) || name AS category, depth, path
FROM tree
ORDER BY path;
-- Bills
-- Electricity | 2 | Bills > Electricity
-- Internet | 2 | Bills > Internet
-- Entertainment
-- Food
-- Groceries | 2 | Food > Groceries
-- Restaurants | 2 | Food > Restaurants ...
-- 2. Total spending for "Food" INCLUDING all its sub-categories
WITH RECURSIVE food_tree AS (
SELECT id FROM categories WHERE name = 'Food'
UNION ALL
SELECT c.id FROM categories c JOIN food_tree f ON c.parent_id = f.id
)
SELECT sum(amount) AS food_total
FROM expenses
WHERE category_id IN (SELECT id FROM food_tree); -- 25370.00
-- 3. Referral chain: everyone who joined through Asha, at any depth
WITH RECURSIVE downline AS (
SELECT id, name, referred_by, 0 AS level, ARRAY[id] AS path
FROM users WHERE name = 'Asha Sharma'
UNION ALL
SELECT u.id, u.name, u.referred_by, d.level + 1, d.path || u.id
FROM users u
JOIN downline d ON u.referred_by = d.id
WHERE NOT u.id = ANY(d.path) -- cycle protection
)
SELECT repeat(' └ ', level) || name AS referral_tree, level
FROM downline
ORDER BY path;
-- Asha Sharma
-- └ Ravi Thapa
-- └ └ Bikash Rai
-- └ Sita Gurung
-- └ └ Maya Karki
-- 4. Generate the numbers 1..5
WITH RECURSIVE n AS (SELECT 1 AS i UNION ALL SELECT i + 1 FROM n WHERE i < 5)
SELECT i FROM n;