Recursive CTEs
in SQL
Learn how queries can call themselves to traverse hierarchies, generate sequences, and solve problems that regular SQL cannot.
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.
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.
Anatomy of a Recursive CTE
The Formal Syntax
How the Engine Executes It
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
Example: Number Sequence
Generate the numbers 1 through 5 without any physical table: pure recursion.
Tracing Each Iteration
Example: Org Chart Traversal
Given an employees table with columns id, name, and manager_id, find all employees under the CEO (id = 1).
Visualizing the Traversal
Example: Bill of Materials
A product is made of components, which themselves contain sub-components. This parts explosion pattern is classic recursion.
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.
Common Mistakes
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
Consider this recursive CTE:
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: