Quick revision
The short answer
We compare each id with the next one using LEAD: SELECT id + 1 AS gap_start, next_id - 1 AS gap_end FROM (SELECT id, LEAD(id) OVER (ORDER BY id) AS next_id FROM ticket) t WHERE next_id - id > 1. A difference greater than 1 means the ids in between are missing. A gap before the first id needs a sentinel row 0, PostgreSQL's generate_series can list every missing value instead, and we should remember that sequences never promise gap-free values.
What to remember
In this answer, we found gaps in a series of ids by comparing each id with the next one using LEAD(id) OVER (ORDER BY id): wherever next_id - id is greater than 1, the gap runs from id + 1 to next_id - 1. A sentinel row 0 reveals a gap before the first id, generate_series(1, max(id)) EXCEPT the existing ids lists every missing value but can be large, and id minus ROW_NUMBER() groups the islands. We also saw that sequences and auto increment leave gaps by design through rollbacks, caching and failed inserts, so gap-free numbers need a counter updated in the same transaction.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We compare each id with the next one using LEAD: SELECT id + 1 AS gap_start, next_id - 1 AS gap_end FROM (SELECT id, LEAD(id) OVER (ORDER BY id) AS next_id FROM ticket) t WHERE next_id - id > 1. A difference greater than 1 means the ids in between are missing. A gap before the first id needs a sentinel row 0, PostgreSQL's generate_series can list every missing value instead, and we should remember that sequences never promise gap-free values.
Why this question is asked
Finding gaps in a series of numbers looks like a puzzle, but it is a real task: missing ticket numbers, missing invoice numbers an auditor asks about, missing days in a sensor feed. It is also the gentlest introduction to a whole family of problems called gaps and islands, where we group rows into runs and find the spaces between them. Interviewers ask it to see whether we reach for window functions, whether we notice the edge case at the start, and whether we understand why the gaps exist in the first place. In this answer, we will set up the data, recap LEAD, write the gap query, handle the gap before the first id, look at the generate_series alternative, find the islands too, and explain why sequences create gaps by design.
1Setting Up the Data and a Quick Recap of LEAD
Our ticket table has ids 1, 2, 3, 7, 8 and 10. The missing ones are 4, 5 and 6, which is one gap, and 9, which is another.
LEAD(id) is a window function that returns the value of id from the next row in the given order, without a self join. LAG does the same for the previous row. The last row has no next row, so LEAD returns NULL there.
2Turning Jumps Into Gaps
If the next id is exactly one more than the current id, nothing is missing. If the difference is greater than 1, every number strictly between them is missing: the gap starts at id + 1 and ends at next_id - 1. We filter in an outer query, because a window function cannot be used in the WHERE of the same query level.
| id | next_id | next_id - id | gap |
|---|---|---|---|
| 2 | 3 | 1 | none |
| 3 | 7 | 4 | (4, 6) |
| 7 | 8 | 1 | none |
| 8 | 10 | 2 | (9, 9) |
| 10 | NULL | NULL | none, last row |
Notice that a single missing number shows up as a gap with the same start and end, (9, 9). The last row's NULL next_id makes next_id - id NULL, and NULL > 1 is not true, so the final row drops out without any special code. The query reads the table once in id order, and with the primary key index it needs no sort.
3The Gap Before the First Id
There is a catch: the query only finds gaps between existing ids. If the series must start at 1 and the table starts at 3, the missing 1 and 2 are invisible, because there is no row before 3 to compare with. The simplest fix is to add a sentinel row 0 to the input, so the first real id has a neighbour.
The same idea works at the other end: if the series must run to a known N, we add a sentinel N + 1 to find missing values after the last id.
4Listing Every Missing Value With generate_series
PostgreSQL can also generate the full expected series and subtract the existing ids. generate_series(1, n) returns one row per integer, and EXCEPT removes the ids that exist.
This handles the start of the series naturally and lists every missing value, which is handy when someone needs the actual numbers. But it builds the whole series, so on a table whose ids reach 500 million with a few large gaps it generates 500 million rows to report a handful of ranges. The LEAD version returns one row per gap, however large the gap is.
5The Other Half: Finding the Islands
Islands are the runs of consecutive ids, here 3, then 7 to 8, then 10. A classic trick finds them: within a run of consecutive numbers, id minus its row number is constant, and it changes at every gap. So we group by that difference.
Gaps and islands are two views of the same data, and in reports it is often clearer to show the islands, such as "tickets 7 to 8 issued", along with the gaps between them.
6Why Sequences Leave Gaps by Design
Before treating gaps as a bug, it is worth knowing that a database sequence or MySQL AUTO_INCREMENT never promises gap-free values. A sequence hands out numbers outside the transaction, so that concurrent inserts never wait for each other. If a transaction takes number 4 and then rolls back, 4 is gone for good. PostgreSQL can also cache sequence values per session, losing the unused ones when the session ends, and an INSERT ... ON CONFLICT DO NOTHING that hits a conflict still consumes a number. A crash can skip values too.
So gaps in an id column are normal and harmless: ids are for identity, not for counting. If the question is "which ticket ids were never used", the query above answers it, but if the business truly needs consecutive numbers, the numbering must come from somewhere else, which is the follow-up below.
7Follow-up questions
Why should an invoice number that must be gap-free not come from a sequence?
Because sequences skip numbers on rollbacks, cached values and failed inserts, by design, so they cannot guarantee consecutive invoice numbers. A gap-free number comes from a counter row updated in the same transaction as the invoice, for example UPDATE invoice_counter SET last = last + 1 RETURNING last; if the transaction rolls back, the increment rolls back too. The price is that invoice creation is serialized on that row, so we assign the number only at the moment of finalizing the invoice.
How would you find gaps in a time series, such as missing minutes of sensor data?
The same way, with timestamps: LEAD(ts) OVER (ORDER BY ts) and a filter on next_ts - ts > interval '1 minute'. For listing every missing minute in PostgreSQL, generate_series accepts timestamps and an interval step.
Does the LEAD query work in MySQL?
Yes. MySQL 8 supports LEAD, LAG and ROW_NUMBER, so the gap and island queries run unchanged; only generate_series is PostgreSQL specific, and in MySQL a recursive CTE can generate the series instead.
8Conclusion
In this answer, we found gaps in a series of ids by comparing each id with the next one using LEAD(id) OVER (ORDER BY id): wherever next_id - id is greater than 1, the gap runs from id + 1 to next_id - 1. A sentinel row 0 reveals a gap before the first id, generate_series(1, max(id)) EXCEPT the existing ids lists every missing value but can be large, and id minus ROW_NUMBER() groups the islands. We also saw that sequences and auto increment leave gaps by design through rollbacks, caching and failed inserts, so gap-free numbers need a counter updated in the same transaction.
Open with
I would use LEAD. In a subquery I select id and lead of id over order by id as next id, so each row sees the next existing id.
Then, if they want more
Then in the outer query I keep rows where next id minus id is greater than one, and return id plus one as the gap start and next id minus one as the gap end. With ids 1, 2, 3, 7, 8, 10 that gives 4 to 6 and 9 to 9.
The filter has to be outside because window functions run after WHERE. The last row has a NULL next id, so the comparison is not true and it drops out on its own.
One edge case: the query only sees gaps between existing rows, so if the series must start at one and the first id is three, I add a sentinel row zero with a union all, and similarly a sentinel at N plus one if the series must end at N.
In PostgreSQL an alternative is generate series from one to max id except the existing ids, which lists every missing value, but on large ranges it generates a lot of rows, while the LEAD version returns one row per gap.
I would also say that gaps in a sequence are normal: sequences and auto increment skip values on rollbacks, caching and failed inserts by design, so a truly gap-free number like an invoice number must come from a counter row updated in the same transaction.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- MySQL 8
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- PostgreSQL documentation, The SQL Language
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Table ticket(id int primary key) should have ids 1 to N with no gaps, but some are...": https://scrivio-interview-library.netlify.app/databases/sql-coding-problems/4bc6e41b22/