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?
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.
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.
The order of things in the WHERE does not matter; the order of the columns in an INDEX does matter, sometimes a lot.
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.)
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 EmployeeId
s, 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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With