TheBoubou
TheBoubou

Reputation: 19903

Finding gap in column with SQL Server

I have a table with a column, int type, it's not the primary key. I have thousand of record.

I'd like to find the missing ids.

I have these data :

1
2
3
4
6
8
11
14

I'd like have this as result : 5,7,9,10,12,13

DO you know how I can do this ?

Thanks,

Upvotes: 0

Views: 52

Answers (2)

David דודו Markovitz
David דודו Markovitz

Reputation: 44921

Assuming mytab is your table, the relevant column is mycol and the potential values are 1-10,000

with t(i) as (select 1 union all select i+1 from t where i<10)
    ,all_values(mycol) as (select row_number() over (order by (select null)) from t t0,t t1,t t2, t t3)
select *
from   all_values a left join mytab t on a.mycol = t.mycol
where  t.mycol is null

Upvotes: 0

Gordon Linoff
Gordon Linoff

Reputation: 1269693

It is easier to get this as ranges:

select (col + 1) as first_missing, (next_col - 1) as last_missing
from (select t.*, lead(col) over (order by col) as next_col
      from t
     ) t
where next_col <> col + 1;

If you actually want this as a list, I would suggest a recursive CTE:

with cte as (
      select t.col, lead(col) over (order by col) as next_col, 1 as lev
      from t
      union all
      select cte.col + 1, next_col, lev + 1
      from cte
      where col + 1 < next_col
     )
select cte.col
from cte
where lev > 1;

Note: If the gaps can be more than 100, you will need OPTION (MAXRECURSION 0).

Here is a db<>fiddle.

Upvotes: 4

Related Questions