Today we are going to explore SQL Server table hints execution plan operation. Consider following SQL query.
USE [AdventureWorks2012]; SELECT * FROM Sales.SalesOrderDetail WHERE SalesOrderDetail.ProductID = 776
In the example, Query optimizer estimates only few records to be returned and it decided to use an Index Seek and Key Lookup (read here Part1, Part2, Part3, Part4) combination in the query followed by Nested Loop Joins (read here Part1, Part2) with Compute Scalar (read here Part1, Part2) to be the efficient plan operators. However, we can force SQL Server to use an INDEX and by doing this we may eliminate Key Lookup operation.
USE [AdventureWorks2012]; SELECT * FROM Sales.SalesOrderDetail WITH (INDEX(PK_SalesOrderDetail_SalesOrderID_SalesOrderDetailID)) WHERE SalesOrderDetail.ProductID = 776
In above example, INDEX hint used to force query optimizer to use a specific index PK_SalesOrderDetail_SalesOrderID_SalesOrderDetailID. This eliminated Key Lookup operation from the plan. We can specify both index id or index name as a target. It is recommended to use name instead or ID as there could an issues with non-clustered indexes as we do not have control on the ID. It is better to check index_id on sys.indexes. Index id 0 is a heap, 1 is a clustered index and value greater than 1 is non clustered index.
Note: This is just an illustration and you should never ever try this method in your production systems.
Stay tuned, I’ll be back again tomorrow.