SQL
Detect Gaps in Sequential IDs with LEAD Function
Efficiently identify missing numbers or gaps in sequential IDs within a database table using the LEAD window function, crucial for data integrity checks.
SELECT
current_id + 1 AS gap_start,
next_id - 1 AS gap_end
FROM (
SELECT
id AS current_id,
LEAD(id, 1) OVER (ORDER BY id) AS next_id
FROM sequential_data
) AS gaps
WHERE next_id IS NOT NULL AND next_id > current_id + 1
ORDER BY gap_start;
How it works: This SQL query efficiently detects gaps in a sequence of numerical IDs within the `sequential_data` table. It uses the `LEAD()` window function to fetch the `id` of the next row based on the `ORDER BY id` sequence. By comparing `current_id` with `next_id`, the query can identify where `next_id` is greater than `current_id + 1`, indicating a gap. The result shows the start and end of each identified gap, useful for data integrity and monitoring.