Query Path 7 — Filter by 2 x NC Indexes
A common indexing dilemma is how to index for multiple where
clause criteria. Is it better to create one composite index that
includes both key columns? Or do two single key column indexes perform
better? Query Paths 7 through 9 evaluate the options.
The following code redefines the indexes: one index keyed on ProductID and one keyed on StartDate.
DROP INDEX Production.WorkOrder.IX_WorkOrder_ProductID;
CREATE INDEX IX_WorkOrder_ProductID
ON Production.WorkOrder (ProductID);
CREATE INDEX IX_WorkOrder_StartDate
ON Production.WorkOrder (StartDate);
With these indexes in place, this query filters by both key columns:
SELECT WorkOrderID, StartDate
FROM Production.WorkOrder
WHERE ProductID = 757
AND StartDate = ‘01/04/2006';
To use both indexes, SQL Server uses a merge join
to request rows from each index seek and then correlates the data to
return the rows that meet both criteria, as shown in Figure 10. This is known as index-intersection. SQL Server makes use of both indexes via separate operations to serve the query.
Examining the performance stat in Table 1, multiple indexes have a query optimizer cost of .12 and use four logical reads.
For infrequent queries, Query Path 7, with its
multiple indexes, is more than adequate and much better than no index
at all. However, for those few queries that run constantly, the next
query path is a better solution for multiple criteria.
Query Path 8 — Filter by Ordered Composite Index
For the raw performance, the fastest
solution to the multiple-where-clause-criteria problem is a single
composite index as demonstrated in Query Path 8.
Creating a composite index with ProductID and StartDate as key columns sets up the test:
DROP INDEX Production.WorkOrder.IX_WorkOrder_ProductID
DROP INDEX Production.WorkOrder.IX_WorkOrder_StartDate
CREATE INDEX IX_WorkOrder_ProductID
ON Production.WorkOrder (ProductID, StartDate);
Rerunning the same query,
SELECT WorkOrderID, StartDate
FROM Production.WorkOrder
WHERE ProductID = 757
AND StartDate = ‘2006-01-04';
The query execution plan, as shown in Figure , is a simple single index seek operation, and it performs wonderfully.