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. 回答1: 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