Detect Gaps in a Sequence

Find missing values in an id sequence by comparing each row with the previous one, a common data-integrity audit query.

SqlData Integrity

Code

sqlsnippet
13 lines
SELECT
    prev_id + 1 AS gap_start,
    id - 1 AS gap_end,
    id - prev_id - 1 AS missing_count
FROM (
    SELECT
        id,
        LAG(id) OVER (ORDER BY id) AS prev_id
    FROM invoices
) numbered
WHERE prev_id IS NOT NULL
  AND id - prev_id > 1
ORDER BY gap_start;

How the snippet works

The statement is SELECT, touching invoices.

Mechanically, the statements are built from: a WHERE clause limiting the rows one statement is allowed to reach; a window function (OVER (…)) taking in surrounding rows without folding them into one; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns.

What to watch for

  • The OVER (…) computation happens post-filter, so referencing it in WHERE fails — wrap it instead.

Applying it

Run the statement against the invoices table.

Statements that matter

SELECT
    prev_id + 1 AS gap_start,
    id - 1 AS gap_end,
    id - prev_id - 1 AS missing_count
FROM (
    SELECT
        id,
        LAG(id) OVER (ORDER BY id) AS prev_id
    FROM invoices
) numbered
WHERE prev_id IS NOT NULL
  AND id - prev_id > 1
ORDER BY gap_start;

Interactive Tools for This Topic

FAQ

What objects does the SQL involve?
`invoices`.