← Back to SQL, page 6

sql-0104 · Medium mid

How does a recursive CTE work? Use it to generate the numbers 1 to 5.

A recursive CTE has an anchor query that produces the starting rows, then UNION ALL, then a recursive query that refers to the CTE itself and produces new rows from the previous step. The engine repeats the recursive part until it returns no rows. A WHERE condition in the recursive part is what stops it.

Full answer
sql
WITH RECURSIVE counter(n) AS (
  SELECT 1
  UNION ALL
  SELECT n + 1 FROM counter WHERE n < 5
)
SELECT n FROM counter;
n
1
2
3
4
5

How the engine runs it:

  1. Run the anchor, SELECT 1. The working set is {1}.
  2. Run the recursive part using only the rows from the last step: from 1 it produces 2.
  3. Repeat with {2}, then {3}, {4}. From 5 the condition n < 5 fails, so the step returns no rows.
  4. Stop, and return everything produced: 1 to 5.

The WHERE n < 5 is the stopping condition. Without it the query never ends; SQLite would keep going until it ran out of memory or hit a LIMIT. A LIMIT on the outer query is a useful safety net while experimenting:

sql
WITH RECURSIVE forever(n) AS (
  SELECT 1 UNION ALL SELECT n + 1 FROM forever
)
SELECT n FROM forever LIMIT 3;
n
1
2
3

The same counter pattern generates dates, which is the everyday use: a calendar of days to LEFT JOIN facts onto.

sql
WITH RECURSIVE days(d) AS (
  SELECT '2026-03-01'
  UNION ALL
  SELECT date(d, '+1 day') FROM days WHERE d < '2026-03-05'
)
SELECT d FROM days;
d
2026-03-01
2026-03-02
2026-03-03
2026-03-04
2026-03-05

PostgreSQL requires the keyword WITH RECURSIVE. SQLite accepts plain WITH too, but writing RECURSIVE keeps the query portable.

sql
WITH RECURSIVE counter(n) AS (
  SELECT 1
  UNION ALL
  SELECT n + 1 FROM counter WHERE n < 5
)
SELECT n FROM counter;

WITH RECURSIVE forever(n) AS (
  SELECT 1 UNION ALL SELECT n + 1 FROM forever
)
SELECT n FROM forever LIMIT 3;

WITH RECURSIVE days(d) AS (
  SELECT '2026-03-01'
  UNION ALL
  SELECT date(d, '+1 day') FROM days WHERE d < '2026-03-05'
)
SELECT d FROM days;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Anchor query, UNION ALL, recursive query referring to the CTE
  • Each step uses only the rows produced by the previous step
  • Recursion stops when a step returns no rows
  • Always include a stopping condition; LIMIT is a safety net

Common mistakes

  • Forgetting the stopping condition
  • Using UNION and relying on it to stop cycles, which only works if rows repeat exactly

Follow-ups

  • How would you generate every month of 2026?
  • How do you stop a recursive CTE that walks a graph with cycles?

Tips

  • Describe the iteration step by step; interviewers want to see the mental model