If I have created a single index on two columns [lastName] and [firstName] in that order. If I then do a query to find the number of the people with first name daniel:
SELECT count(*)
FROM people
WHERE firstName = N'daniel'
will this search in each section of the first index (lastname) and use the secondary index (firstName) to quickly search through each of the blocks of LastName entries?
This seems like an obvious thing to do and I assume that it is what happens but you know what they say about assumptions.
Yes, this query may – and probably do – use this index (and do an Index Scan) if the query optimizer thinks that it’s better to “quickly search through each of the blocks of LastName entries” as you say than (do an Full Scan) of the table.
An index on
(firstName)would be more efficient though for this particular query so if there is such an index, SQL-Server will use that one (and do an Index Seek).Tested in SQL-Server 2008 R2, Express edition:
Query without any index, Table Scan:
Query with index on
(lastName, firstName), Index Scan:Query with index on
(firstName), Index Seek: