Search code examples
sqlpostgresqlgaps-and-islands

How Do I Find a Gap In a Sequence in PostgreSQL?


I have a table of items with an id and a number_col. There are plenty of questions on Stackoverflow for finding gaps in IDs, but what I'm looking for is a gap in the number. For example, if I have 3 items:

id | number_col
===============
1  | 1
1  | 2
1  | 4

I need a SQL query that returns id = 1, number_col = 3 as missing. The query should look at the max value in number_col for each id. Since 4 is the max number_col value for id 1 in my example, it should not return that 1, 5 is missing.


Solution

  • If you want ranges of missing values, then:

    select number_col + 1 as first_missing, (next_nc - 1) as last_missing
    from (select t.*, lead(number_col) over (partition by id order by number_col) as next_nc
          from t
         ) t
    where next_nc <> number_col + 1