0

So i have a very strange issue, If i run a query like this:

SELECT * 
FROM tbl_x 
WHERE tbl_x.SomeCode IN ('1','2','3','4','5','6')

The query uses the index on the table, however if i do query this:

SELECT * 
FROM tbl_x 
WHERE tbl_x.SomeCode IN ('1','2','3','4','5','6','7')

The query ignores the index and decides to do a Table Scan

Why is MS SQL Server not using the index when there are more than 6 values in the Where clause?

Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275
Mike Bateman
  • 360
  • 2
  • 9
  • IF an index is very fragmented (say 50%) SQL Server might decide to just scan rather than use the index since it thinks this is the "cheaper" plan. – Mark Schultheiss Apr 25 '23 at 15:30

1 Answers1

0

I guess that based on data distribution and cardinality query optimizer decides to use full table scan, because it is cheaper than to use index.

You could check:

SELECT COUNT(*)
FROM tbl_x;

and

SELECT COUNT(*)
FROM tbl_x
WHERE tbl_x.SomeCode IN ('1','2','3','4','5','6','7');

Probably you exceeded 20% rows of entire table.

Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275