// SQL snippet

Detect gaps in an id sequence

Compare each id with the one after it using LEAD; when the difference is more than one, the ids in between are missing.

Main statement
All engines

The task

orders uses a plain integer id and someone wants to know whether rows were ever hard-deleted. Consecutive ids with a jump mean ids in between were used and are now gone.

The snippet

Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.

All engines
WITH adjacent AS (
  SELECT id,
         LEAD(id) OVER (ORDER BY id) AS next_id
  FROM orders
)
SELECT id AS last_id_before_gap,
       next_id AS first_id_after_gap,
       next_id - id - 1 AS missing_ids
FROM adjacent
WHERE next_id - id > 1
ORDER BY id;

So funktioniert es

LEAD(id) looks one row ahead in id order, pairing every id with its successor. Window functions cannot appear in WHERE, so the CTE computes next_id first and the outer query keeps jumps of two or more. next_id - id - 1 is how many ids the jump skipped. The last row's next_id is NULL, so it drops out of the comparison on its own.

Variations

Summarize total missing ids

WITH adjacent AS (
  SELECT id, LEAD(id) OVER (ORDER BY id) AS next_id
  FROM orders
)
SELECT COUNT(*) AS gap_count,
       COALESCE(SUM(next_id - id - 1), 0) AS total_missing_ids
FROM adjacent
WHERE next_id - id > 1;

Questions that come up

Do sequence gaps always mean deleted rows?

No. Rolled-back transactions and failed inserts burn sequence values in most databases, so a gap can be an aborted insert rather than a delete. Treat this query as a change detector worth explaining, not proof of data loss. The missing-sequence-values recipe lists the actual ids if you need to probe them.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.