Dev Helpers

SQL / Recursive queries

Count down to zero

Dev Helpers · December 3, 2025

A recursive query needs both an initial row and a terminating condition. Walk through the boundary to see whether zero is included.

Worked example

WITH RECURSIVE t(n) AS (VALUES(5) UNION ALL SELECT n-1 FROM t WHERE n>0) SELECT n FROM t;

Result

[
  {
    "n": 5
  },
  {
    "n": 4
  },
  {
    "n": 3
  },
  {
    "n": 2
  },
  {
    "n": 1
  },
  {
    "n": 0
  }
]

Implementation notes

Without a termination condition, recursive expansion can consume far more work than the result suggests. Bound a production traversal independently of sample data.

Try it yourself

Start at zero and at one and compare the final rows.

Open the SQL example →

Editorial date December 3, 2025 · Published December 6, 2026

Related articles

Compare two literal lists

Set operations compare rows under SQL's rules for duplicates. Check whether the result represents membership or the number of occurrences.

Count jobs per active day

Grouping timestamps by day produces counts only for days present in the data. A continuous chart may need a calendar series as well.