sql server - SQL Select first missing value in a series -


i asked following: have table (lets call tbl) , has 1 column of type int (let call num) , had sequential numbers in it:

num ---  1  2  4  5  6  8  9  11 

now need write query returns first missing number (in example answer 3).

here's answer (works):

select top 1 (num + 1) tbl (num + 1) not in (select num tbl) 

after writing this, asked, if tbl contained 10 million records - how improve performence (because myinner query cause full table scan).

my thoughts index in on num field , doing not exists. love hear alternatives.

here approach using row_number:

sql fiddle

;with ctern as(     select *,         rn = num - row_number() over(order num)     tbl ) select top 1 num - rn ctern rn > 0 order num asc 

with proper index on num, here stats under million row test harness.

original - not in     : cpu time = 296 ms,  elapsed time = 289 ms wewesthemenace        : cpu time = 0 ms,  elapsed time = 0 ms notulysses(not exists): cpu time = 687 ms,  elapsed time = 679 ms. 

Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -