There are many scenarios where we may in need to identify the missing numbers in the provided range.
Here is the quick query which help in identifying using CTE [Common Table Expression]:
DECLARE @Test TABLE
(
Num INT
)
INSERT INTO @Test VALUES (1)
INSERT INTO @Test VALUES (2)
INSERT INTO @Test VALUES (4)
INSERT INTO @Test VALUES (5)
INSERT INTO @Test VALUES (8)
INSERT INTO @Test VALUES (9)
INSERT INTO @Test VALUES (10)
--Get the Missing Numbers from the sequence
;WITH Missing (minid, maxid)
AS
(
SELECT 0 AS minid, 10
UNION ALL
SELECT minid + 1, maxid FROM Missing
WHERE minid < maxid
)
SELECT minid
FROM Missing
LEFT OUTER JOIN @Test tt on tt.Num = Missing.minid
WHERE tt.Num is NULL
OPTION (MAXRECURSION 0);
Result:
minid
0
3
6
7