01 / 21

Recursive CTEs
in SQL

Learn how queries can call themselves to traverse hierarchies, generate sequences, and solve problems that regular SQL cannot.

SQL Database Programming

What is a CTE?

A Common Table Expression (CTE) is a temporary, named result set that you define at the beginning of a query using the WITH keyword. Think of it as a named subquery you can reference later: it exists only for the duration of that single statement.

WITH my_cte AS ( SELECT id, name FROM employees WHERE department = 'Engineering' ) SELECT * FROM my_cte;

Why Do We Need Recursion?

Some data has hierarchical or graph-like relationships: employees reporting to managers, folders inside folders, or network routes. A regular query cannot follow these chains to an unknown depth.

Org Charts
Find every employee under a VP, no matter how many levels deep.
File Systems
List all subfolders and files within a root directory.
Sequences
Generate a series of numbers or dates without a physical table.

Anatomy of a Recursive CTE

ANCHOR MEMBER The starting rows (base case) UNION ALL RECURSIVE MEMBER References the CTE itself Repeats until no new rows

The Formal Syntax

WITH RECURSIVE cte_name AS ( -- Anchor member: base case SELECT columns FROM base_table WHERE starting_condition UNION ALL -- Recursive member: references cte_name SELECT columns FROM base_table JOIN cte_name ON relationship ) SELECT * FROM cte_name;

How the Engine Executes It

1
Run the anchor. Execute the first SELECT to produce the initial set of rows.
2
Feed results into the recursive member. The CTE name now refers to the rows just produced.
3
Collect new rows. The recursive SELECT runs and produces zero or more new rows.
4
Repeat or stop. If new rows were produced, go back to step 2. If not, stop: the recursion is complete.
5
Combine everything. All rows from every iteration are UNION ALL'd into the final result set.

Regular vs Recursive CTEs

Regular CTE Recursive CTE
Self-referencing No Yes
Keyword WITH WITH RECURSIVE
UNION ALL Optional Required
Terminates After one execution When no new rows
Use case Readability, reuse Hierarchies, sequences

How to Write a Recursive CTE

1
Identify the starting point. What is the root or seed row? This becomes your anchor member.
2
Define the relationship. How does one row connect to the next? Write a JOIN between the base table and the CTE name.
3
Ensure termination. The recursive member must eventually return zero rows. Usually the JOIN condition naturally exhausts the data.
4
Connect with UNION ALL. Place the anchor above, the recursive member below, separated by UNION ALL.
5
Query the CTE. Write your final SELECT referencing the CTE name, adding filters, ordering, or aggregations as needed.

Example: Number Sequence

Generate the numbers 1 through 5 without any physical table: pure recursion.

WITH RECURSIVE nums AS ( SELECT 1 AS n -- anchor: start at 1 UNION ALL SELECT n + 1 -- recursive: add 1 FROM nums WHERE n < 5 -- stop condition ) SELECT n FROM nums;

Tracing Each Iteration

Anchor
\(n = 1\)
Iter 1
\(n = 2\)
Iter 2
\(n = 3\)
Iter 3
\(n = 4\)
Iter 4
\(n = 5\)
STOP: \(n=5\) fails \(n < 5\)
FINAL RESULT 1 2 3 4 5

Example: Org Chart Traversal

Given an employees table with columns id, name, and manager_id, find all employees under the CEO (id = 1).

WITH RECURSIVE org AS ( -- Anchor: start at the CEO SELECT id, name, manager_id, 0 AS depth FROM employees WHERE id = 1 UNION ALL -- Recursive: find direct reports SELECT e.id, e.name, e.manager_id, org.depth + 1 FROM employees e JOIN org ON e.manager_id = org.id ) SELECT * FROM org;

Visualizing the Traversal

Alice (CEO) depth 0 Bob (VP Eng) depth 1 Carol (VP Sales) depth 1 Dave depth 2 Eve depth 2 Frank depth 2 Each iteration discovers the next level of the tree

Example: Bill of Materials

A product is made of components, which themselves contain sub-components. This parts explosion pattern is classic recursion.

WITH RECURSIVE parts AS ( SELECT part_id, part_name, parent_id, 1 AS level FROM components WHERE parent_id IS NULL -- top-level product UNION ALL SELECT c.part_id, c.part_name, c.parent_id, p.level + 1 FROM components c JOIN parts p ON c.parent_id = p.part_id ) SELECT * FROM parts ORDER BY level, part_name;

The Termination Condition

Recursive CTEs stop when the recursive member returns zero rows. If it never returns zero rows, you get an infinite loop and the database will eventually error out.

Natural Stop
Hierarchical data: the JOIN finds no more children. No WHERE needed.
WHERE Clause
Sequences: explicitly cap with a condition like WHERE \(n < 100\).
Safety Net
Use settings like MAXRECURSION (SQL Server) or cte_max_recursion_depth (MySQL) to set a hard limit.

Common Mistakes

✕ Missing UNION ALL
Using UNION (without ALL) silently removes duplicates and can break the recursion or cause unexpected results.
✕ No Stop Condition
Forgetting a WHERE clause in sequence generation or not accounting for cyclic data leads to infinite loops.
✕ Wrong JOIN Direction
Joining child.id = cte.id instead of child.parent_id = cte.id reverses the traversal and produces wrong results.

Summary at a Glance

Concept Key Detail
Keyword WITH RECURSIVE
Anchor Member The base case: starting rows
Recursive Member References the CTE name
Connector UNION ALL (required)
Termination When recursive member returns 0 rows
Common Use Cases Hierarchies, sequences, graphs
Danger Infinite loops if no stop condition

Question 1 of 5

What are the two required parts of a recursive CTE?

Question 2 of 5

What keyword connects the anchor member and the recursive member?

Question 3 of 5

When does a recursive CTE stop executing?

Question 4 of 5

What will the last value of n be in the result set?

Question 5 of 5

In an org chart recursive CTE, the anchor member typically selects: