Full answer
sql
CREATE TABLE invoices (no INTEGER PRIMARY KEY);
INSERT INTO invoices VALUES (1), (2), (3), (6), (7), (9), (12);sql
SELECT no + 1 AS gap_start, next_no - 1 AS gap_end FROM (
SELECT no, LEAD(no) OVER (ORDER BY no) AS next_no FROM invoices
) WHERE next_no - no > 1 ORDER BY gap_start;| gap_start | gap_end |
|---|---|
| 4 | 5 |
| 8 | 8 |
| 10 | 11 |
Three gaps appear: 4 to 5, 8 on its own, and 10 to 11. Reporting ranges keeps the output small even when a gap is large; a recursive CTE or a numbers table could list every missing value individually if needed. The last row has no LEAD and is excluded by the filter, so numbers missing after the maximum are not reported, which is usually right. In PostgreSQL, generate_series(min, max) EXCEPT SELECT no is an alternative for listing each missing number.
sql
CREATE TABLE invoices (no INTEGER PRIMARY KEY);
INSERT INTO invoices VALUES (1), (2), (3), (6), (7), (9), (12);
SELECT no + 1 AS gap_start, next_no - 1 AS gap_end FROM (
SELECT no, LEAD(no) OVER (ORDER BY no) AS next_no FROM invoices
) WHERE next_no - no > 1 ORDER BY gap_start;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- LEAD pairs each row with the next
- A difference above 1 marks a gap
- Report ranges, not every value
- generate_series EXCEPT lists values in PostgreSQL
Common mistakes
- Self-joining on no + 1, which finds gap starts but not ends
- Generating huge number lists for sparse gaps
Follow-ups
- How would you list each missing number?
- Why do auto-increment ids have gaps?
Tips
- Show gap ranges