SQL
Find Gaps in a Numeric Sequence
Discover how to locate missing IDs or gaps in a continuous numeric sequence within your SQL table. Essential for auditing and ensuring data completeness.
SELECT
t1.id + 1 AS missing_id
FROM
your_table t1
LEFT JOIN
your_table t2 ON t1.id + 1 = t2.id
WHERE
t2.id IS NULL
ORDER BY
missing_id
LIMIT 1;
How it works: This query identifies the first missing ID in a sequence. It performs a `LEFT JOIN` on the table itself, checking if `t1.id + 1` exists in `t2.id`. If `t2.id` is `NULL` for a given `t1.id`, it signifies a gap, meaning `t1.id + 1` is missing from the table.