Let’s say we have this values in the database:
num --- 1 2 4 5 6 8 9 11
To Find the first missing value, we can use this:
;WITH CteRN AS( SELECT *, RN = num - ROW_NUMBER() OVER(ORDER BY num) FROM tbl ) SELECT TOP 1 num - RN FROM CteRN WHERE RN > 0 ORDER BY num ASC