Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find gaps of a sequence 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 a SQL that gives me the following result:

gap_start | gap_end
4         | 4
7         | 9

How can i write a SQL to perform such query? I am using PostgreSQL.

like image 702
Mateus Viccari Avatar asked May 11 '15 13:05

Mateus Viccari


People also ask

How does mysql determine gaps in sequential numbering?

If there is a sequence having gap of maximum one between two numbers (like 1,3,5,6) then the query that can be used is: select s.id+1 from source1 s where s.id+1 not in(select id from source1) and s.id+1<(select max(id) from source1);

How do I find missing numbers in mysql?

How do I find missing numbers in mysql? In order to find out which cards are missing, we need to know where the gaps are in the sequential numbering. You can use generate series to generate numbers from 1 to the highest id of your table. Then run a query where id not in this series.


1 Answers

With modern SQL, this can easily be 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

like image 63
a_horse_with_no_name Avatar answered Oct 02 '22 23:10

a_horse_with_no_name