Blog Post

SQL – How to Find Missing Sequence in a table

,

Problem statement:-

 A table with identity column have ‘n’ rows in that few rows are deleted. How to find which rows are deleted?

Download code :- MissingRows

Solution:-

create table MissingRowDemo (a int);
insert into MissingRowDemo values (7001);
insert into MissingRowDemo values (7002);
insert into MissingRowDemo values (7004);
insert into MissingRowDemo values (7005);
insert into MissingRowDemo values (7006);
insert into MissingRowDemo values (7010);
  
WITH Missing (missnum, maxid)
AS
(
 SELECT  (select min(a) missnum from MissingRowDemo) , (select max(a) from MissingRowDemo)
 UNION ALL
 SELECT missnum + 1, maxid FROM Missing
 WHERE missnum < maxid
)
SELECT missnum
FROM Missing
LEFT OUTER JOIN MissingRowDemo tt on tt.a = Missing.missnum
WHERE tt.a is NULL
OPTION (MAXRECURSION 0);

Output:-

MissingRows

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating