Recursive CTEs for Hierarchical Data Queries
How to query hierarchical data with recursive Common Table Expressions in SQL, covering tree traversal, org charts, category trees, and cycle detection.
Overview
A recursive Common Table Expression (CTE) lets a query reference itself, so you can walk through hierarchical data stored in a single table. It’s got two moving parts: an anchor member that picks the starting rows, and a recursive member that joins those rows back to the source table. That combination handles org charts, category trees, file systems, threaded comments, and any parent-child relationship tied together with a self-referencing foreign key. Working with large datasets? Check out batch processing patterns for efficient bulk operations. The examples here work in PostgreSQL 16+, MySQL 8.0+, SQLite 3.8.4+, SQL Server 2019+, Oracle 21c+, Snowflake, BigQuery, and DuckDB 0.10+ — the syntax is similar across engines, with minor differences noted in the Variants section.
When to Use
Use a recursive CTE when you need to walk a hierarchy from a known starting point. Common cases include finding every direct and indirect report under a manager, listing all subcategories under a parent category, traversing a directory tree, fetching a comment and all its replies, exploding a bill of materials into components, or following transitive dependencies.
When NOT to Use
Skip the recursive CTE for flat queries that don’t traverse hierarchy; a regular CTE or a subquery is simpler. It also isn’t the right tool for very deep hierarchies (some databases hit recursion limits), graph traversal with cycles (recursive CTEs don’t handle cycles natively), or shortest-path problems (use a graph database or algorithm for those).
Solution
Basic recursive CTE structure
WITH RECURSIVE hierarchy AS (
-- Anchor member: starting point
SELECT
id,
parent_id,
name,
1 AS depth
FROM categories
WHERE parent_id IS NULL
UNION ALL
-- Recursive member: join back to the CTE
SELECT
c.id,
c.parent_id,
c.name,
h.depth + 1 AS depth
FROM categories c
INNER JOIN hierarchy h ON c.parent_id = h.id
)
SELECT * FROM hierarchy ORDER BY depth, name;
Org chart: all reports of a specific manager
WITH RECURSIVE reports AS (
-- Anchor: direct reports of manager 5
SELECT
employee_id,
manager_id,
employee_name,
1 AS depth,
CAST(manager_id AS VARCHAR(1000)) AS path
FROM employees
WHERE manager_id = 5
UNION ALL
-- Recursive: reports of reports
SELECT
e.employee_id,
e.manager_id,
e.employee_name,
r.depth + 1,
r.path || ' -> ' || CAST(e.manager_id AS VARCHAR)
FROM employees e
INNER JOIN reports r ON e.manager_id = r.employee_id
)
SELECT
employee_id,
employee_name,
depth,
path
FROM reports
ORDER BY depth, employee_name;
Category tree with full path
WITH RECURSIVE category_tree AS (
SELECT
id,
parent_id,
name,
CAST(name AS VARCHAR(1000)) AS full_path,
1 AS depth
FROM categories
WHERE parent_id IS NULL
UNION ALL
SELECT
c.id,
c.parent_id,
c.name,
ct.full_path || ' / ' || c.name,
ct.depth + 1
FROM categories c
INNER JOIN category_tree ct ON c.parent_id = ct.id
)
SELECT
id,
name,
full_path,
depth
FROM category_tree
ORDER BY full_path;
Find all ancestors (bottom-up traversal)
WITH RECURSIVE ancestors AS (
-- Anchor: starting node
SELECT
id,
parent_id,
name,
1 AS depth
FROM categories
WHERE id = 42 -- Start from a specific node
UNION ALL
-- Recursive: go up to parent
SELECT
c.id,
c.parent_id,
c.name,
a.depth + 1
FROM categories c
INNER JOIN ancestors a ON c.id = a.parent_id
)
SELECT * FROM ancestors ORDER BY depth DESC;
Aggregating across hierarchy
If you need to aggregate data across a hierarchy — say, counting products per category including subcategories — you can pair the recursive CTE with a pandas ETL pipeline for downstream processing, or do it all in SQL:
WITH RECURSIVE category_tree AS (
SELECT id, parent_id, name, 1 AS depth
FROM categories
WHERE parent_id IS NULL
UNION ALL
SELECT c.id, c.parent_id, c.name, ct.depth + 1
FROM categories c
INNER JOIN category_tree ct ON c.parent_id = ct.id
)
SELECT
ct.id,
ct.name,
ct.depth,
COUNT(p.id) AS product_count,
COALESCE(SUM(p.price), 0) AS total_value
FROM category_tree ct
LEFT JOIN products p ON p.category_id = ct.id
GROUP BY ct.id, ct.name, ct.depth
ORDER BY ct.depth, ct.name;
Roll-up: sum child values to all ancestors
WITH RECURSIVE descendants AS (
SELECT id, parent_id, name, amount, 1 AS depth
FROM nodes
WHERE id = 1 -- Root node
UNION ALL
SELECT
n.id,
n.parent_id,
n.name,
n.amount,
d.depth + 1
FROM nodes n
INNER JOIN descendants d ON n.parent_id = d.id
),
rollup AS (
SELECT
d.id,
d.name,
SUM(child.amount) AS total_descendant_amount
FROM descendants d
INNER JOIN descendants child
ON child.id = d.id OR child.depth > d.depth
-- This approach is simplified; a more accurate rollup
-- requires building the path and checking containment
GROUP BY d.id, d.name
)
SELECT * FROM rollup ORDER BY total_descendant_amount DESC;
Cycle detection
WITH RECURSIVE traversal AS (
SELECT
id,
parent_id,
CAST(id AS VARCHAR(1000)) AS path,
1 AS depth,
false AS has_cycle
FROM nodes
WHERE id = 1
UNION ALL
SELECT
n.id,
n.parent_id,
t.path || ' -> ' || CAST(n.id AS VARCHAR),
t.depth + 1,
POSITION(CAST(n.id AS VARCHAR) IN t.path) > 0 AS has_cycle
FROM nodes n
INNER JOIN traversal t ON n.parent_id = t.id
WHERE t.has_cycle = false
AND t.depth < 100 -- Safety limit
)
SELECT * FROM traversal WHERE has_cycle = true;
PostgreSQL 14+ can do the cycle check for you with the CYCLE clause, which marks rows that close a loop:
WITH RECURSIVE org_tree AS (
SELECT employee_id, manager_id, employee_name FROM employees WHERE manager_id IS NULL
UNION ALL
SELECT e.employee_id, e.manager_id, e.employee_name
FROM employees e
JOIN org_tree ot ON e.manager_id = ot.employee_id
)
CYCLE employee_id SET is_cycle TO true DEFAULT false USING cycle_path
SELECT * FROM org_tree WHERE NOT is_cycle;
Limiting recursion depth
WITH RECURSIVE limited_tree AS (
SELECT id, parent_id, name, 1 AS depth
FROM categories
WHERE parent_id IS NULL
UNION ALL
SELECT c.id, c.parent_id, c.name, lt.depth + 1
FROM categories c
INNER JOIN limited_tree lt ON c.parent_id = lt.id
WHERE lt.depth < 5 -- Only 5 levels deep
)
SELECT * FROM limited_tree ORDER BY depth, name;
Bill of materials explosion
WITH RECURSIVE bom AS (
-- Anchor: top-level assembly
SELECT
component_id,
assembly_id,
quantity,
1 AS level,
CAST(component_id AS VARCHAR(1000)) AS component_path
FROM bill_of_materials
WHERE assembly_id = 'PRODUCT-001'
UNION ALL
-- Recursive: components of components
SELECT
b.component_id,
b.assembly_id,
b.quantity * bom.quantity AS total_quantity,
bom.level + 1,
bom.component_path || ' -> ' || CAST(b.component_id AS VARCHAR)
FROM bill_of_materials b
INNER JOIN bom ON b.assembly_id = bom.component_id
)
SELECT
component_id,
level,
total_quantity,
component_path
FROM bom
ORDER BY level, component_id;
Explanation
Here’s what happens under the hood when you run a recursive CTE. The database engine evaluates the anchor
member first — your starting point, the root rows where parent_id IS NULL. Whatever the anchor
returns becomes the working set the recursive member joins against. Then the engine runs the recursive member, which joins the working set back
to the source table. The new rows produced by that join get added to the working set, and the process repeats
until the recursive member produces no new rows. That’s the termination condition: when the join returns
nothing new, the recursion stops.
The UNION ALL combines all intermediate results into the final output. UNION (without ALL) would
deduplicate at each step, which adds overhead you almost never need in a tree traversal — each row is
a unique path from root to node.
Most engines default to depth-first traversal. Each branch gets followed all the way to its leaf
before the engine backtracks and moves to the next sibling. If you want breadth-first output (all
nodes at depth 1, then all at depth 2, etc.), add ORDER BY depth to the final query. The traversal order and the output order are separate concerns — the
engine builds the full result set before applying your ORDER BY.
Performance depends on three things: the size of the hierarchy, whether parent_id is indexed, and how deep
the recursion goes. Without an index on parent_id, each recursive step does a full table scan. On a
10,000-row table with 5 levels of depth, that’s 5 full scans instead of 5 index lookups. I’ve seen recursive
CTEs go from 30 seconds to under 100ms just by adding CREATE INDEX idx_parent ON categories(parent_id).
Different engines have different recursion limits. SQL Server defaults to 100 levels (override with
OPTION (MAXRECURSION N)). PostgreSQL has no hard limit but will hit memory constraints on very deep
trees. MySQL 8.0+ defaults to 1000 iterations. Snowflake and BigQuery handle deep recursion well but charge
by data scanned, so a recursive CTE on a large table can get expensive fast.
Three more tuning knobs worth knowing. If the recursive CTE gets referenced more than once in the same query,
PostgreSQL 12+ lets you force a single computation with WITH RECURSIVE t AS MATERIALIZED (...). Deep trees
accumulate intermediate rows in memory, so bump work_mem for the session if EXPLAIN ANALYZE shows temp
file spills. Speaking of which — run EXPLAIN ANALYZE and look at the iteration count of the recursive
member: hundreds of iterations usually means a missing index on the join column or a cycle you didn’t expect.
One gotcha I’ve hit more than once: cyclic data. If your parent-child relationships contain a cycle (A → B → C → A), the recursive CTE will loop forever — or until it hits the recursion limit and errors out. That’s why the cycle detection pattern earlier in this recipe matters. Always add a depth limit as a safety net, even if you think your data is acyclic. Data migrations, bad imports, and manual edits can introduce cycles into what should be a clean tree.
Variants
PostgreSQL: using ARRAY for path
WITH RECURSIVE category_tree AS (
SELECT
id,
parent_id,
name,
ARRAY[id] AS path,
1 AS depth
FROM categories
WHERE parent_id IS NULL
UNION ALL
SELECT
c.id,
c.parent_id,
c.name,
ct.path || c.id,
ct.depth + 1
FROM categories c
INNER JOIN category_tree ct ON c.parent_id = ct.id
WHERE c.id != ALL(ct.path) -- Cycle prevention
)
SELECT id, name, path, depth FROM category_tree ORDER BY path;
MySQL 8.0+: recursive CTE syntax
WITH RECURSIVE org_tree AS (
SELECT employee_id, manager_id, employee_name, 1 AS level
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.employee_id, e.manager_id, e.employee_name, ot.level + 1
FROM employees e
JOIN org_tree ot ON e.manager_id = ot.employee_id
)
SELECT * FROM org_tree WHERE level <= 3 ORDER BY level;
SQL Server: no RECURSIVE keyword needed
WITH org_tree AS (
SELECT employee_id, manager_id, employee_name, 1 AS level
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.employee_id, e.manager_id, e.employee_name, ot.level + 1
FROM employees e
JOIN org_tree ot ON e.manager_id = ot.employee_id
)
SELECT * FROM org_tree OPTION (MAXRECURSION 100);
Snowflake: using CONNECT BY (alternative)
SELECT
employee_id,
manager_id,
employee_name,
LEVEL AS depth,
SYS_CONNECT_BY_PATH(employee_name, ' -> ') AS path
FROM employees
START WITH manager_id IS NULL
CONNECT BY PRIOR employee_id = manager_id
ORDER SIBLINGS BY employee_name;
Best Practices
- Always include a
depthorlevelcolumn. You’ll thank me when debugging — and it gives you a cheap way to cap recursion. - Add a safety limit such as
WHERE depth < Nto prevent infinite recursion on cyclic data. - Use
UNION ALLinstead ofUNION;UNIONdeduplicates, which adds overhead you usually don’t need. - Build a path column for debugging so you can see the exact traversal route.
- Test with small datasets first; recursive CTEs can be slow on large tables. For aggregations across large hierarchies, consider Spark groupBy aggregation.
- Index
parent_idandid; the recursive join hits those columns repeatedly. - SQL Server users can bump the default 100-level limit with
OPTION (MAXRECURSION N).
For a deeper guide, see Transform Data in the Warehouse with dbt.
Common Mistakes
- Forgetting the anchor member. Without a starting point the CTE returns nothing; the anchor has to select rows that don’t depend on the CTE.
- Using
UNIONinstead ofUNION ALLfor no reason.UNIONdeduplicates results and adds overhead, so useUNION ALLunless you actually need deduplication. - Skipping cycle detection. Cyclic data causes infinite recursion, so add a path column and check for repeats, or add a depth limit.
- Not indexing
parent_id. The recursive join doesJOIN c ON c.parent_id = h.id; without an index onparent_id, each level becomes a full table scan. - Expecting breadth-first order. Recursive CTEs return depth-first by default. Use
ORDER BY depthif you want breadth-first output.
Summary
- A recursive CTE has two parts: an anchor member (base case) and a recursive member (joins back to the CTE). The engine runs the anchor, then loops the recursive member until no new rows are produced.
- Use
UNION ALL, notUNION— deduplication adds overhead you don’t need in tree traversal. - Always add a depth limit (
WHERE depth < N) as a safety net against cyclic data, even if you think your tree is clean. - Index
parent_id— without it, each recursive step does a full table scan. I’ve seen 30s → 100ms just from adding one index. - Most engines default to depth-first output. Add
ORDER BY depthif you want breadth-first. - Supported in PostgreSQL 16+, MySQL 8.0+, SQLite 3.8.4+, SQL Server 2019+, Oracle 21c+, Snowflake,
BigQuery, and DuckDB 0.10+. Syntax is pretty similar; some engines require the
RECURSIVEkeyword, some don’t.
Companion code: The sql-cte-recursive-hierarchy companion repo has runnable SQL scripts with test data for every example above, plus a multi-database setup guide.
See Also
Frequently Asked Questions
What is a recursive CTE?
A recursive CTE is one that references itself. It's got an anchor member (the base case) and a recursive member (the part that joins back to the CTE). The database evaluates the anchor first, then keeps applying the recursive member until it stops producing new rows.
Which databases support recursive CTEs?
Most modern SQL engines support them: PostgreSQL, MySQL 8.0+, SQLite 3.8.4+, SQL Server (2008+), Oracle
(11gR2+), Snowflake, BigQuery, and DuckDB. The syntax is pretty similar across engines. Some require the RECURSIVE
keyword, some don't (SQL Server, for example).
How do I prevent infinite recursion?
Add a depth limit such as WHERE depth < 100, or track visited nodes in a path array or string and check for
repeats. SQL Server also gives you OPTION (MAXRECURSION N) as a secondary guard.
Does LIMIT stop the recursion early?
No. LIMIT N on the outer query only truncates the output — the engine still computes the full recursive
result set first. For true early termination you need the stop condition inside the recursive member
(WHERE depth < N), or FETCH FIRST N ROWS ONLY in engines that support it.
What is the difference between recursive CTE and CONNECT BY?
CONNECT BY is Oracle's proprietary syntax, also supported by Snowflake. Recursive CTEs follow
the SQL standard, so they're the safer bet for portability. CONNECT BY is more concise but less
flexible, so pick recursive CTEs when you need to move between engines.
Can I use recursive CTEs for graph traversal?
For simple trees without cycles, yes. Once cycles or shortest-path problems show up, a graph database or graph algorithm is a better fit. Recursive CTEs don't support cycle detection natively, so you've got to build that part yourself.
Related Resources
SQL CTEs: Common Table Expressions Explained
A practical guide to SQL CTEs: non-recursive and recursive expressions, readability, performance, and when to use them over subqueries.
RecipeFind and Remove Duplicate Rows in SQL
Detect duplicate records in SQL tables using GROUP BY and HAVING, then remove them safely while keeping the canonical row.
RecipeRank Rows and Calculate Running Totals with Window Functions
Use SQL window functions to rank rows, compute running totals, and compare values within partitions without self-joins.
RecipeAnalyze and Optimize SQL Indexes with EXPLAIN
Identify missing, unused, and inefficient indexes by reading execution plans and measuring query cost with EXPLAIN.
DocDatabase Schema Documentation Template
A template for documenting database schemas with entity relationships, field definitions, and migration history.
RecipeBatch Processing Patterns
Design reliable batch processing pipelines for large datasets with retry logic, idempotency, and observability.