Full answer
sql
WITH inv(n) AS (VALUES (1),(2),(3),(6),(7),(11),(12))
SELECT n + 1 AS gap_start, next_n - 1 AS gap_end
FROM (SELECT n, LEAD(n) OVER (ORDER BY n) AS next_n FROM inv)
WHERE next_n - n > 1
ORDER BY gap_start;| gap_start | gap_end |
|---|---|
| 4 | 5 |
| 8 | 10 |
Numbers 4 and 5 are missing, and so are 8 to 10. Each row with a jump produces one range.
For short ranges, a recursive CTE can list each missing number individually, which suits small audits:
sql
WITH RECURSIVE inv(n) AS (VALUES (1),(2),(3),(6),(7),(11),(12)),
all_n(n) AS (SELECT MIN(n) FROM inv UNION ALL SELECT n + 1 FROM all_n WHERE n < (SELECT MAX(n) FROM inv))
SELECT n AS missing FROM all_n WHERE n NOT IN (SELECT n FROM inv) ORDER BY n;| missing |
|---|
| 4 |
| 5 |
| 8 |
| 9 |
| 10 |
Sequences generated by the database (autoincrement, PostgreSQL sequences) are not gap-free by design: rolled-back inserts and cached values leave holes. If legal rules require gap-free invoice numbers, assign them in a separate step under a lock, not from a sequence.
sql
WITH inv(n) AS (VALUES (1),(2),(3),(6),(7),(11),(12))
SELECT n + 1 AS gap_start, next_n - 1 AS gap_end
FROM (SELECT n, LEAD(n) OVER (ORDER BY n) AS next_n FROM inv)
WHERE next_n - n > 1
ORDER BY gap_start;
WITH RECURSIVE inv(n) AS (VALUES (1),(2),(3),(6),(7),(11),(12)),
all_n(n) AS (SELECT MIN(n) FROM inv UNION ALL SELECT n + 1 FROM all_n WHERE n < (SELECT MAX(n) FROM inv))
SELECT n AS missing FROM all_n WHERE n NOT IN (SELECT n FROM inv) ORDER BY n;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- LEAD compares each value with the next
- A jump greater than 1 is a gap
- Ranges come from current + 1 to next - 1
- Database sequences are not gap-free
Common mistakes
- Generating every number up to MAX to find gaps on huge tables
- Assuming auto-increment ids never skip
Follow-ups
- How would you find gaps in dates instead?
- How would you allocate gap-free invoice numbers?
Tips
- Mention why sequences have gaps