Sub topic 4
Your first recursive query: generating a series
This chapter assumes you can write a basic WITH clause (a common table expression, or CTE) and read the anchor, UNION ALL, and recursive member layout from the previous chapter. You should also be comfortable with SELECT, WHERE, LEFT JOIN, and GROUP BY. Here you will build recursive queries that need no tables at all: number series and date series. These are the simplest recursive queries, and they show the evaluation loop clearly.
Why start with a series
A series query reads no stored data. The anchor member supplies one starting row, and the recursive member computes each next row from the previous one. Because nothing else is involved, you can see exactly what the recursion does.
Series are also useful in practice:
- A calendar of dates lets you report days that have no data.
- A list of numbers can drive a test data generator.
- A sequence of values can feed a loop-like calculation, such as compound interest by month.
The smallest useful query
WITH RECURSIVE n(i) AS (
SELECT 1
UNION ALL
SELECT i + 1 FROM n WHERE i < 10
)
SELECT i FROM n;This returns the numbers 1 through 10. The query has three parts:
n(i)names the CTE and its one column. The recursive member refers tonby this name.SELECT 1is the anchor member. It runs once and produces the first row.SELECT i + 1 FROM n WHERE i < 10is the recursive member. It reads the rows produced by the previous step and produces new rows from them.
The database repeats the recursive member until it returns no rows. Then it stops and hands every row collected so far to the outer SELECT.
Tracing the iterations
Each pass reads only the rows created by the pass before it, not the whole result so far. Here is the trace for the series query:
| Step | Input rows | `WHERE i < 10` | Rows produced |
|---|---|---|---|
| Anchor | none | not applicable | 1 |
| Pass 1 | 1 | true | 2 |
| Pass 2 | 2 | true | 3 |
| ... | ... | ... | ... |
| Pass 9 | 9 | true | 10 |
| Pass 10 | 10 | false | none |
Pass 10 produces nothing, so the loop ends.
The working table is the set of rows from the latest pass. Each pass replaces it with new rows. The result table only grows.
The off-by-one rule
The WHERE clause tests the input row, not the row being produced. With WHERE i < 10, an input of 9 yields 10, and an input of 10 yields nothing. The last value in the output is therefore 10.
If you write WHERE i <= 10, an input of 10 still passes, and you get 11 as well. When a series has one row too many or too few, check which side of the comparison you tested.
Changing the start and the step
The anchor sets the first value and the recursive expression sets the step. This query counts by fives from 0 to 50:
WITH RECURSIVE steps(v) AS (
SELECT 0
UNION ALL
SELECT v + 5 FROM steps WHERE v < 50
)
SELECT v FROM steps;The stop test is v < 50, and the last input that passes is 45, which produces 50. A step of 5 lands exactly on 50. With a step of 7, the loop would end at 49 because 49 passes v < 50 and produces 56, so 56 would appear. If the step does not divide the range evenly, the series can overshoot your upper bound. Filter in the outer query when you need a hard limit:
WITH RECURSIVE steps(v) AS (
SELECT 0
UNION ALL
SELECT v + 7 FROM steps WHERE v < 50
)
SELECT v FROM steps WHERE v <= 50;Carrying more than one column
A recursive CTE can carry several columns, and each new row can use all the columns of the previous row. This query computes factorials:
WITH RECURSIVE fact(n, f) AS (
SELECT 1, CAST(1 AS bigint)
UNION ALL
SELECT n + 1, f * (n + 1) FROM fact WHERE n < 20
)
SELECT n, f FROM fact;The cast in the anchor matters. In most databases the column types come from the anchor member. A plain 1 is a 32-bit integer in PostgreSQL, so the product would overflow around 13!. Casting the anchor to bigint makes the column wide enough. The largest factorial that fits in a signed 64-bit integer is 20!, which is why the query stops at 20.
Generating a date series
Date series follow the same pattern. The anchor is a start date, the step adds one day, and the stop test compares to an end date. In PostgreSQL:
WITH RECURSIVE days(d) AS (
SELECT DATE '2026-01-01'
UNION ALL
SELECT d + 1 FROM days WHERE d < DATE '2026-01-07'
)
SELECT d FROM days;Adding the integer 1 to a date gives a date. If you wrote d + INTERVAL '1 day' instead, the result would be a timestamp, and PostgreSQL would reject the query because the column type in the recursive member does not match the anchor. You would fix that with (d + INTERVAL '1 day')::date.
SQLite has no date type, so it stores dates as text and uses the date() function to step:
WITH RECURSIVE days(d) AS (
SELECT '2026-01-01'
UNION ALL
SELECT date(d, '+1 day') FROM days WHERE d < '2026-01-07'
)
SELECT d FROM days;This works because ISO 8601 text (YYYY-MM-DD) sorts in date order, so the text comparison d < '2026-01-07' behaves like a date comparison.
Putting a series to work: filling gaps
The most common use of a date series is to report days that have no rows. Suppose daily_sales(sale_date, amount) has no rows for days with no sales. A plain GROUP BY would skip those days. Joining from a generated calendar fixes that. This is PostgreSQL syntax:
WITH RECURSIVE days(d) AS (
SELECT DATE '2026-01-01'
UNION ALL
SELECT d + 1 FROM days WHERE d < DATE '2026-01-31'
)
SELECT days.d,
COALESCE(SUM(s.amount), 0) AS total
FROM days
LEFT JOIN daily_sales s ON s.sale_date = days.d
GROUP BY days.d
ORDER BY days.d;The LEFT JOIN keeps every calendar day. Days without sales have a NULL amount, and COALESCE turns the resulting NULL sum into 0. The series is the left side of the join. If you put daily_sales on the left, the missing days would vanish again.
Recursion limits differ by database
A series query stops because of its WHERE clause. Databases also add their own safety limits, and a long series can hit them even when your query is correct.
| Database | Keyword | Default limit | How to change it |
|---|---|---|---|
| PostgreSQL | `WITH RECURSIVE` | none | none built in |
| MySQL 8.0+ | `WITH RECURSIVE` | 1000 iterations (`cte_max_recursion_depth`) | `SET SESSION cte_max_recursion_depth = 5000;` |
| SQLite | `WITH RECURSIVE` | none | a `LIMIT` clause can cap rows |
| SQL Server | `WITH` (no `RECURSIVE`) | 100 levels | `OPTION (MAXRECURSION n)` |
SQL Server also drops the RECURSIVE keyword. This query counts to 1000 and raises the level limit to match:
WITH n AS (
SELECT 1 AS i
UNION ALL
SELECT i + 1 FROM n WHERE i < 1000
)
SELECT i FROM n
OPTION (MAXRECURSION 1000);Without the hint, SQL Server stops with an error once the series passes 100 levels. OPTION (MAXRECURSION 0) removes the limit, so use it only when your stop condition is certain.
Common errors in series queries
- Missing or unreachable stop condition. Without a
WHEREclause, or with one that never fails (such asWHERE i > 0on a rising series), the query never ends. - Off-by-one bounds. Using
<=where you meant<, or the reverse, gives one extra or one missing row. - Type mismatch between the anchor and the recursive member. An integer anchor with a decimal step, or a
dateanchor with atimestampstep, fails in PostgreSQL and can truncate values in other databases. Cast the anchor to the widest type you need. - Forgetting the column list or alias. The recursive member must produce the same number of columns, in the same order, as the anchor. In SQL Server, name the columns with aliases in the anchor, as in
SELECT 1 AS i. - Hitting the dialect limit. An error mentioning "maximum recursion" means the series is longer than the default allows, not that the query is wrong.
Exercise
Write a PostgreSQL recursive query that returns the first day of each month in 2026 (12 rows). Which part of the query decides that the output stops at December?
Show answer
WITH RECURSIVE months(m) AS ( SELECT DATE '2026-01-01' UNION ALL SELECT (m + INTERVAL '1 month')::date FROM months WHERE m < DATE '2026-12-01' ) SELECT m FROM months; The WHERE clause in the recursive member decides it. When m is 2026-12-01, the test m < DATE '2026-12-01' is false, so the recursive member returns no rows and the loop ends. The cast to date keeps the column type equal to the anchor, because adding an interval to a date produces a timestamp.
Exercise
A query starts at 1, uses SELECT i + 3 FROM n WHERE i < 20, and returns 1, 4, 7, 10, 13, 16, 19, 22. Why is 22 in the output, and how do you remove it without changing the recursive member?
Show answer
The input 19 passes the test 19 < 20, so it produces 22. The test applies to the input row, not the new row. Add WHERE i <= 20 to the outer SELECT (SELECT i FROM n WHERE i <= 20) to remove 22.