Skip to content
Advertisement

Find the smallest unused number in SQL Server

How do you find the smallest unused number in a SQL Server column?

I am about to import a large number of manually recorded records from Excel into a SQL Server table. They all have a numeric ID (called document number), but they weren’t assigned sequentially for reasons that no longer apply, meaning from now on when my web site records a new record, it needs to assign it the smallest possible document number (greater than zero) that has not already been taken.

Is there a way to do this through plain SQL or is this a problem for TSQL/code?

Thanks!

EDIT

Special thanks to WW for raising the issue of concurrency. Given that this is a web app, it is multi-threaded by definition and anyone faced with this same problem should consider either a code or DB level lock to prevent a conflict.

LINQ

FYI – this can be accomplished via LINQ with the following code:

nextNewNum == 5

Advertisement

Answer

Find the first row where there does not exist a row with Id + 1

Edit:

To handle the special case where the lowest existing id is not 1, here is a ugly solution:

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement