CodeBlanks Logo Icon CodeBlanks

Stopping recursion

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 < 5

This 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

query.sql
-- stop condition
SELECT n + 1 FROM countdown

Sample solution

query.sql
SELECT n + 1 FROM countdown WHERE n < 5

Expected 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

Question
SELECT n + 1 FROM countdown ____ n < 5
Answer
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.

All lessons in Advanced