Introduction
Sometimes, you want to find missing numbers in a list that should be in order. This helps to spot gaps or missing data.
Sometimes, you want to find missing numbers in a list that should be in order. This helps to spot gaps or missing data.
SELECT current_value + 1 AS gap_start, next_value - 1 AS gap_end FROM ( SELECT value AS current_value, LEAD(value) OVER (ORDER BY value) AS next_value FROM your_table ) sub WHERE next_value > current_value + 1;
LEAD() looks at the next row's value in order.
This query finds where the next number is more than 1 greater than the current, showing gaps.
SELECT current_num + 1 AS gap_start, next_num - 1 AS gap_end FROM ( SELECT num AS current_num, LEAD(num) OVER (ORDER BY num) AS next_num FROM numbers ) t WHERE next_num > current_num + 1;
SELECT id + 1 AS missing_id FROM ( SELECT id, LEAD(id) OVER (ORDER BY id) AS next_id FROM employees ) e WHERE next_id > id + 1;
This example finds gaps in the sequence of numbers 1,2,3,7,8,10. It shows missing numbers between these.
WITH numbers(num) AS ( VALUES (1), (2), (3), (7), (8), (10) ) SELECT num + 1 AS gap_start, next_num - 1 AS gap_end FROM ( SELECT num, LEAD(num) OVER (ORDER BY num) AS next_num FROM numbers ) sub WHERE next_num > num + 1;
If the sequence has no gaps, the query returns no rows.
Make sure the column you check is numeric and sorted properly.
Use LEAD() to compare each number with the next one.
Find gaps where the next number is more than 1 greater.
This helps find missing or skipped numbers in sequences.
LEAD() function when finding gaps in a sequence of numbers in SQL?LEAD() function allows you to look at the next row's value in the current row's context.LEAD() to find gaps in a sequence column named num in table numbers?LEAD(column) OVER (ORDER BY column) to define the order for the window function.LEAD(num) OVER (ORDER BY num), which is the correct form to get the next number in order.numbers with column num containing values (1, 2, 4, 5, 7), what will the following query return?SELECT num, LEAD(num) OVER (ORDER BY num) AS next_num FROM numbers;
num value ordered by num. So each row shows its own num and the next number.num sequence but returns no rows:SELECT num FROM numbers WHERE LEAD(num) OVER (ORDER BY num) - num > 1;
orders with an integer column order_id that should be sequential but may have missing numbers. Which query correctly finds all missing order_id values between the minimum and maximum present?generate_series from minimum to maximum order_id to create all possible IDs.Pass the test and this pattern moves unknown