Another Method to Identify Missing Values in Numeric Sequences

Who is online?  0 guests and 1 members
Home  »  Blogs  »  kylewalker  »  Another Method to Identify Missing Values in Numeric Sequences
 
0
/5
Avg: 0/5: (0 votes)

Comments (1)

bradschu
bradschu said:

This is a perfect candidate for the use of a Numbers table.

If you have the following Numbers table (i.e. all the integers from 1 to 1,000,000) in existence in your database...

;with 
  L0(c) as (select 0 union all select 0 union all select 0)        --3 Rows
 ,L1(c) as (select 0 from L0 a cross join L0 b cross join L0 c)    --27 Rows (3x3x3)
 ,L2(c) as (select 0 from L1 a cross join L1 b cross join L1 c)    --19683 Rows (27x27x27)
 ,L3(c) as (select 0 from L2 a cross join L2 b)                    --387,420,489 Rows (19683x19683)
 ,NN(n) as (select row_number() over (order by (select 0)) from L3)
select n into dbo.Nums from NN where n<=1000000

create unique clustered index IX_Nums on dbo.Nums (n)

 

...then you could execute the following query to, for example, find the missing ProductID's in AdventureWorks' Production.Product table:

select n 
from Nums
where n between (select min(ProductID) from Production.Product) 
            and (select max(ProductID) from Production.Product)
  and not exists (select *
                  from Production.Product 
                  where n=ProductID)

 

This will incur no Writes and will take a fraction of the CPU and Reads compared to the looping method.

--Brad

6/28/2010
 · 
 
by
Blogs RSS Feed

kylewalker's latest blog posts

Blogs RSS Feed

Latest community blog posts