Gap Detection In Sequence

Find missing numbers in a sequence with window functions for data integrity checks.

SqlData Integrity

Code

sqlsnippet
10 lines
WITH numbered AS (
  SELECT id, ROW_NUMBER() OVER (ORDER BY id) AS rn
  FROM sequence_items
)
SELECT
  prev.id + 1 AS gap_start,
  curr.id - 1 AS gap_end
FROM numbered prev
JOIN numbered curr ON curr.rn = prev.rn + 1
WHERE curr.id > prev.id + 1;

How the snippet works

What runs is SELECT, with sequence_items and numbered as the object involved.

In terms of clauses, the statements use: a CTE (WITH … AS) that names an intermediate result before the main query; one JOIN combining rows across tables; a WHERE clause limiting the rows one statement is allowed to reach; a window function (OVER (…)) working across rows while keeping each row in the result; an ORDER BY that fixes the output order.

What to watch for

  • To filter on a window function’s result you need an outer query or CTE; the same-level WHERE runs too early.

Applying it

Run it in the sequence_items database context.

Statements that matter

WITH numbered AS (
SELECT id, ROW_NUMBER() OVER (ORDER BY id) AS rn
FROM sequence_items
)
SELECT
prev.id + 1 AS gap_start,
curr.id - 1 AS gap_end
FROM numbered prev
JOIN numbered curr ON curr.rn = prev.rn + 1
WHERE curr.id > prev.id + 1;

Interactive Tools for This Topic

FAQ

Which objects does the SQL touch?
The references are `sequence_items`, `numbered`, with one join tying the pair together.