Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
QA interview question
Databases, SQL & BISQL languageMiddleCommonPractical

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

Solution · Find gaps in a sequence
Dialect · Portable SQLRuntime · SQLite sample DB

Runs against the resettable SQLite sample database used by the playground.

SQL
SQLite · sample DB · browser sandbox
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.

#sql#lag#sequence#data-quality

Sources

PostgreSQL documentationPostgreSQL Global Development Group · Relational modelling, SQL, joins, constraints, transactions, concurrency, indexes, query plans and recovery