Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do indexes work with "IN" clause

Tags:

sql

indexing

If I have a query like:

Select EmployeeId  From Employee  Where EmployeeTypeId IN (1,2,3) 

and I have an index on the EmployeeTypeId field, does SQL server still use that index?

like image 603
lomaxx Avatar asked Aug 28 '08 02:08

lomaxx


People also ask

Can we use index in where clause?

You should always add an index on any field to be used in a WHERE clause (whether for SELECT, UPDATE, or DELETE). The type of index depends on the type of data in the field and whether you need each row to have a unique value.

Under what conditions should the indexes avoid?

Indexes should not be used on tables containing few records. Tables that have frequent, large batch updates or insert operations. Indexes should not be used on columns that contain a high number of NULL values. Indexes should not be used on the columns that are frequently manipulated.

Does where clause order matter for index?

The order of things in the WHERE does not matter; the order of the columns in an INDEX does matter, sometimes a lot.

Can we use index in CTE?

Indexes can not be added to a CTE. However, in the CTE select adding an ORDER BY clause on the joined fields reduced the execution time from 20 minutes or more to under 10 seconds. (You need to also ADD SELECT TOP 100 PERCENT to allow an ORDER BY in a CTE select.)


1 Answers

Yeah, that's right. If your Employee table has 10,000 records, and only 5 records have EmployeeTypeId in (1,2,3), then it will most likely use the index to fetch the records. However, if it finds that 9,000 records have the EmployeeTypeId in (1,2,3), then it would most likely just do a table scan to get the corresponding EmployeeIds, as it's faster just to run through the whole table than to go to each branch of the index tree and look at the records individually.

SQL Server does a lot of stuff to try and optimize how the queries run. However, sometimes it doesn't get the right answer. If you know that SQL Server isn't using the index, by looking at the execution plan in query analyzer, you can tell the query engine to use a specific index with the following change to your query.

SELECT EmployeeId FROM Employee WITH (Index(Index_EmployeeTypeId )) WHERE EmployeeTypeId IN (1,2,3) 

Assuming the index you have on the EmployeeTypeId field is named Index_EmployeeTypeId.

like image 55
Kibbee Avatar answered Sep 21 '22 03:09

Kibbee