Home > Ask the SQL Server Experts > Tony Bain Questions & Answers > Finding gaps in column of sequential numbers
Ask The SQL Server Expert: Questions & Answers
EMAIL THIS

Finding gaps in column of sequential numbers

Tony Bain EXPERT RESPONSE FROM: Tony Bain

Pose a Question
Other SQL Server Categories
Meet all SQL Server Experts
Become an Expert for this site


Digg This!    StumbleUpon Toolbar StumbleUpon    Bookmark with Delicious Del.icio.us   


>
QUESTION POSED ON: 11 November 2003
How do I write a routine that will find gaps in a column of sequential numbers? For example: the employee table has a column named deptno (0001, 0002, 0005, etc,), and I want to find all the gaps.

>

The script below should help you with this. The performance of this is relative to the number of rows within your employee table.

For the purpose of this example I will create a fake employees table. In real life you would replace this with your existing one.

create table dbo.EmployeesExample
(
 EmpID char(4) PRIMARY KEY,
 FirstName varchar(50),
 LastName varchar(50)
)

insert dbo.EmployeesExample VALUES('0001','Laura','Jones')
insert dbo.EmployeesExample VALUES('0003','Stephanie','Smith')
insert dbo.EmployeesExample VALUES('0017','William','Black')
insert dbo.EmployeesExample VALUES('0020','Linda','White')

Now this is the code that finds the missing values.

create table #MissingIDS
(
 EmpId char(4) PRIMARY KEY
)

declare @maxid  int,
 @currentid int

--Find the current maximum employee id
SELECT @maxid=max(cast(empid as int)) FROM dbo.EmployeesExample

select @currentid=1

--Loop around sequentially populating the temporary table with every
--possible employee id
while @currentid<@maxid
begin
 insert #MissingIDS select right('0000'+cast(@currentid as
varchar(4)),4)
 select @currentid=@currentid+1
end

--delete the existing employee ids from the temporary table
--by joining to the Employees table
delete #MissingIDS
from #MissingIDS m
inner join dbo.EmployeesExample e on m.empid=e.empid

--And what you have left is the missing ids
select * from #MissingIDS

drop table #MissingIDS
A slight variation on this checks to see if the empid exists before inserting into the temporary table, thereby eliminating the need for the delete.

Now this is the code that finds the missing values.

create table #MissingIDS
(
 EmpId char(4) PRIMARY KEY
)

declare @maxid  int,
 @currentid int

--Find the current maximum employee id
SELECT @maxid=max(cast(empid as int)) FROM dbo.EmployeesExample

select @currentid=1

--Loop around sequentially populating the temporary table with every
--possible employee id
while @currentid<@maxid 
begin
 if not exists(select empid from dbo.EmployeesExample where
EmpID=right('0000'+cast(@currentid as varchar(4)),4))
  insert #MissingIDS select right('0000'+cast(@currentid as
varchar(4)),4)
 
 select @currentid=@currentid+1
end

--And what you have left is the missing ids
select * from #MissingIDS

drop table #MissingIDS

For More Information


Digg This!    StumbleUpon Toolbar StumbleUpon    Bookmark with Delicious Del.icio.us   



RELATED CONTENT
Tony Bain
Application not resolving username and password
Problems trying to install SQL Server on a two-node cluster on SAN
Error connecting to Web-based application
Conversion of char datatype to datetime datatype resulted in an out of range datetime value
Getting error when dropping, inserting into or truncating table with QA
Often used SP wiped out the database
Tony's SQL Server book for DBAs
Exporting T-SQL scripts from command line
Oracle SQL doesn't work in SQL Server
Recovering the database from the MDF file

RELATED RESOURCES
2020software.com, trial software downloads for accounting software, ERP software, CRM software and business software systems
Search Bitpipe.com for the latest white papers and business webcasts
Whatis.com, the online computer dictionary



Search and Browse the Expert Answer Center
Search and browse more than 25,000 question and answer pairs from more than 250 TechTarget industry experts.
Browse our Expert Advice



SQL Solutions - SQL Database Design
HomeNewsTopicsITKnowledge ExchangeTipsAsk the ExpertsMultimediaWhite PapersIT Downloads
About Us  |  Contact Us  |  For Advertisers  |  For Business Partners  |  Site Index  |  RSS
SEARCH 
TechTarget provides technology professionals with the information they need to perform their jobs - from developing strategy, to making cost-effective purchase decisions and managing their organizations' technology projects - with its network of technology-specific websites, events and online magazines.

TechTarget Corporate Web Site  |  Media Kits  |  Site Map




All Rights Reserved, Copyright 2005 - 2009, TechTarget | Read our Privacy Policy
  TechTarget - The IT Media ROI Experts