Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find "holes" in a table

Tags:

sql

I recently inherited a database on which one of the tables has the primary key composed of encoded values (Part1*1000 + Part2).
I normalized that column, but I cannot change the old values. So now I have

select ID from table order by ID
ID
100001
100002
101001
...

I want to find the "holes" in the table (more precisely, the first "hole" after 100000) for new rows.
I'm using the following select, but is there a better way to do that?

select /* top 1 */ ID+1 as newID from table
where ID > 100000 and
ID + 1 not in (select ID from table)
order by ID

newID
100003
101029
...

The database is Microsoft SQL Server 2000. I'm ok with using SQL extensions.

like image 857
pmg Avatar asked Oct 06 '08 14:10

pmg


2 Answers

select ID +1 From Table t1
where not exists (select * from Table t2 where t1.id +1 = t2.id);

not sure if this version would be faster than the one you mentioned originally.

like image 61
Thorsten Avatar answered Oct 07 '22 15:10

Thorsten


SELECT (ID+1) FROM table AS t1
LEFT JOIN table as t2
ON t1.ID+1 = t2.ID
WHERE t2.ID IS NULL
like image 20
Santiago Palladino Avatar answered Oct 07 '22 15:10

Santiago Palladino