Filtered Index with WHERE col IN (...) clause

I was asked if it is possible to create an filtered index with a WHERE col IN (…) clause and then use WHERE col = n with n being one of the values of the (…) list

So let’s create a small sample

create table idx
(
ID int NOT NULL IDENTITY(1,1) primary key clustered,
Data int
)
insert into idx (Data) values (1)
go 100
insert into idx (Data) values (2)
go 2
insert into idx (Data) values (3)
go 2

create index idx1 on idx(ID)
where Data in (2,3)

select ID from idx where Data in (2, 3) -- Index is used

select ID from idx where Data = 2 -- Table scan

select ID from idx where Data in (2, 3) AND Data = 2 -- Table scan

-- But that’s not because SQL is not smart we created the index wrong

drop index idx1 on idx

create index idx1 on idx(ID)
INCLUDE (Data) -- if the data we filter on is not in the index SQL has to do a lookup on the table
where Data in (2,3) -- and therefore chooses to make an full table scan

select ID from idx where Data in (2, 3) -- Index is used

select ID from idx where Data = 2 -- Index is used !!!! THATS what we wanted

select ID from idx where Data = 1 -- Table scan as expected

No feedback yet
Leave a comment

Your email address will not be revealed on this site.
PoorExcellent
(Line breaks become <br />)
(For my next comment on this site)
(Allow users to contact me through a message form -- Your email will not be revealed!)
This is a captcha-picture. It is used to prevent mass-access by robots.
Please enter the characters from the image above. (case sensitive)
Trackback address for this post
This is a captcha-picture. It is used to prevent mass-access by robots.
Please enter the characters from the image above. (case sensitive)