Click here to Skip to main content
15,885,067 members
Articles / Programming Languages / SQL

SQL: How to Find Holes in Sequences

Rate me:
Please Sign up or sign in to vote.
3.06/5 (5 votes)
17 Jun 2009CPOL 26.7K   8   3
How to find hole in sequences in SQL

Have you ever been asked to find all holes in document numbers (docs are sequentially numbered)? I had to do this search twice. Once for auditing purposes: holes may mean some sort of forgery. And now customers want to reuse numbers of deleted docs. And how do you think holes can be found using SQL? Assume we have:

SQL
create table tbl (id int identity primary key); 

So, there is nothing easier than intersect tab to itself with incremented id.

SQL
select id+1 from tbl 
except 
select id from tbl; 

This query returns all holes. The result is list of missed id ranges begins. Ends of missed id ranges can be got with similar query.

SQL
select id-1 from tbl 
except 
select id from tbl; 

I also need the function for the minimum free doc number. This is it:

SQL
select top 1 * from 
( 
   select id+1 as id from tbl 
   except 
   select id from tbl 
) t; 

See you on .

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
Russian Federation Russian Federation
I have started as a C++ developer in far 2000. I'd been developing banking and treasury software for 3 years using C++. In 2003 I switched to .NET at DELL. After that I worked as a project manager on different projects (internal audit, treasury automation, publishing house automation, etc.). Since 2009 I own a small software company specialized in SaaS services and develop a DotNetNuke modules.

Comments and Discussions

 
QuestionSuggestion using PL/SQL for holes with more than 1 value Pin
Mario Guarino 202210-Nov-22 0:54
Mario Guarino 202210-Nov-22 0:54 
QuestionMy vote of 1 Pin
Herman<T>.Instance20-Apr-16 23:55
Herman<T>.Instance20-Apr-16 23:55 
GeneralMy vote of 5 Pin
Jörgen Sigvardsson28-Sep-10 0:58
Jörgen Sigvardsson28-Sep-10 0:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.