Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find missing numbers in a sequence in MS SQL

Tags:

sql

sql-server

Say i have a table with an integer column Id. I need to find the missing numbers in a sequence with a maximum returned amount.

  • If the table is empty and i'm asking for 10, it should return the numbers 1-10.
  • If the table has 1-5 and i'm asking for 10, it should return the numbers 6,7,8,9,10,11,12,13,14,15.
  • If the table has 1,2,4,6,9 and im asking for 10, it should return the numbers 3,5,7,8,10,11,12,13,14,15

How can i achive this in one single query using MS SQL?

Thanks in advance!

like image 472
Lasse O Avatar asked Nov 18 '25 20:11

Lasse O


2 Answers

Try this:

If you need to get more numbers, just increase the WHERE Number<=100.

DECLARE @Tab1 TABLE (ID INT)

INSERT INTO @Tab1 VALUES(1)
INSERT INTO @Tab1 VALUES(3)
INSERT INTO @Tab1 VALUES(5)
INSERT INTO @Tab1 VALUES(7)
INSERT INTO @Tab1 VALUES(9)

;WITH CTE AS
(
    SELECT 1 AS Number
    UNION ALL
    SELECT Number + 1 FROM CTE
    WHERE Number<=100
)
SELECT TOP 5 *
FROM CTE
WHERE Number NOT IN(SELECT ID FROM @Tab1)
ORDER BY Number
OPTION (maxrecursion 0);

Existing values:

Number
1
3
5
7
9

OutPut:

Number
2
4
6
8
10

Hope this helps you.

like image 82
DineshDB Avatar answered Nov 21 '25 12:11

DineshDB


This should work
There are also a system table with numbers

declare @T table (i int primary key);
insert into @T values (1), (2), (4), (6), (9); 
declare @count int = 10;
declare @size int = (select count(*) from @T);
with cte as
( select 1 as num
  union all 
  select num + 1 
  from cte
  where num + 1 <= (@count + @size)
)
select top (@count) cte.num 
from cte 
left join @T t 
  on t.i = cte.num 
where t.i is null 
order by cte.num 
option ( MaxRecursion 0 );
like image 29
paparazzo Avatar answered Nov 21 '25 12:11

paparazzo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!