Stopping recursion
- SQL course
- Advanced
- Lesson 11/81
- 4 min
Learn when a recursive CTE stops.
Stopping recursion
In a recursive CTE the condition goes in the recursive part's WHERE. It stops when the condition fails.
SELECT n + 1 FROM countdown WHERE n < 5This query stops when n reaches 5.
n + 1 is selected from countdown. WHERE keeps only the rows where n < 5 holds.
Stopping recursion — details
Without a condition, infinite recursion occurs. Databases usually guard with a depth limit.
You put the stop condition in the WHERE of the recursive part (e.g. WHERE n < 5). In PostgreSQL, forgetting it can make the query run until memory runs out.
Practice Stopping recursion
Ensure stopping with a WHERE n < 5 condition in the recursive CTE.
Starter code
-- stop condition
SELECT n + 1 FROM countdownSample solution
SELECT n + 1 FROM countdown WHERE n < 5Expected output
n 2 3 4 5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Add WHERE
SELECT n + 1 FROM countdown ____ n < 5
SELECT n + 1 FROM countdown WHERE n < 5
Explanation: WHERE n < 5 is the stop condition; once it fails the recursion produces no new rows.
2 Stopping recursion: match the terms
| Term | Meaning |
|---|---|
condition |
stop |
WHERE |
filter |
infinite |
danger |
limit |
depth |
3 When does a recursive CTE stop?
- Never
- Always
- When the condition is no longer met Correct answer
- Automatically
Explanation: It stops when the condition fails.