Write SQL to find gaps in an expected numeric sequence such as invoice numbers or event versions.
Answer
Order the sequence and use LAG to compare each value with its predecessor. When the current value is greater than previous + 1, the missing interval starts at previous + 1 and ends at current - 1. First confirm that continuity is actually a business invariant because many generated identifiers may legally have gaps.
Strong answer includes
- uses ordered LAG or an equivalent gap-detection technique
- returns the missing interval rather than only flagging a row
- checks whether sequence continuity is a real requirement
Practical example
Dialect · Portable SQLRuntime · SQLite sample DB
Runs against the resettable SQLite sample database used by the playground.
SQL
Result
Run the query to see the result.
Compare each sequence value with its predecessor. This checks numeric continuity, not whether every generated identifier must legally exist.
Expected result: One row per missing numeric interval.