List missing values in an id sequence
A recursive CTE walks every integer from the smallest to the largest id; an anti-join keeps only the values with no matching row.
The task
sequence-gap-detection told you there are 37 missing ids in orders; now you need the actual numbers to check archives or restore them.
The snippet
Written for PostgreSQL. Versions for SQL Server are under Variations.
WITH RECURSIVE
bounds AS (SELECT MIN(id) AS lo, MAX(id) AS hi FROM orders),
seq(id) AS (
SELECT lo FROM bounds
UNION ALL
SELECT s.id + 1 FROM seq s, bounds b WHERE s.id < b.hi
)
SELECT s.id AS missing_id
FROM seq s
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.id = s.id)
ORDER BY s.id;
Fonctionnement
bounds reads MIN and MAX once; the recursive member adds 1 until it reaches the maximum, producing every integer in the range, and the NOT EXISTS anti-join drops the ids that exist. This exact statement also runs on MySQL 8.0+ and SQLite. MySQL stops recursion at 1,000 levels by default (cte_max_recursion_depth), so raise that setting for a wider id range.
Variations
SQL Server: no RECURSIVE keyword
SQL ServerWITH bounds AS (SELECT MIN(id) AS lo, MAX(id) AS hi FROM orders),
seq(id) AS (
SELECT lo FROM bounds
UNION ALL
SELECT s.id + 1 FROM seq s, bounds b WHERE s.id < b.hi
)
SELECT s.id AS missing_id
FROM seq s
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.id = s.id)
ORDER BY s.id
OPTION (MAXRECURSION 0); -- lifts the 100-level default; Oracle runs the rest without this line
PostgreSQL: generate_series one-liner
PostgreSQLSELECT missing_id
FROM generate_series(
(SELECT MIN(id) FROM orders),
(SELECT MAX(id) FROM orders)
) AS g(missing_id)
WHERE NOT EXISTS (
SELECT 1 FROM orders o WHERE o.id = g.missing_id
);
Questions that come up
How large can the id range be before this gets slow?
The CTE materializes one row per integer in the range, so a table spanning ids 1 to 10 million generates 10 million sequence rows even if the table is small. For wide, sparse ranges, run sequence-gap-detection first and only enumerate the ranges it reports, or restrict the sequence with a WHERE inside the recursive member.
Keep reading
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.