Find sequence spaces in SQL without creating additional 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 SQL to give me the following output:
gap_start | gap_end
4 | 4
7 | 9
How can I write SQL to execute such a query? I am using PostgreSQL.
+3
source to share
2 answers
With modern SQL, this can be easily done using window functions :
select invoice_number + 1 as gap_start,
next_nr - 1 as gap_end
from (
select invoice_number,
lead(invoice_number) over (order by invoice_number) as next_nr
from invoices
) nr
where invoice_number + 1 <> next_nr;
SQLFiddle: http://sqlfiddle.com/#!15/1e807/1
+15
source to share
I found another request:
select invoice_number + lag gap_start,
invoice_number + lead - 1 gap_end
from (select invoice_number,
invoice_number - lag(invoice_number) over w lag,
lead(invoice_number) over w - invoice_number lead
from invoices window w as (order by invoice_number)) x
where lag = 1 and lead > 1;
+1
source to share