Skip to content
Advertisement

Find gaps of a sequence in PostgreSQL tables

I have a table invoices with a field invoice_number. This is what happens when i execute select invoice_number from invoice

invoice_number
1
2
3
5
6
10
11

I want a SQL that gives me the following result:

gap_start gap_end
1 3
5 6
10 11

Advertisement

Answer

demo:db<>fiddle

You can use row_number() window function to create a row count and use the difference to your actual values as group criterion:

SELECT
    MIN(invoice) AS start,
    MAX(invoice) AS end
FROM (
    SELECT
        *,
        invoice - row_number() OVER (ORDER BY invoice) as group_id
    FROM t
) s
GROUP BY group_id
ORDER BY start
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement