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.
Code
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 inWHEREfails — 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
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- What objects does the SQL involve?
- `invoices`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.