I have this query:
select top 500 * from clicks
where domainid = 'AC8BBCA4-1CC4-456E-9A85-E7A5C0D7E981'
order by clickedOn
I wonder which index will perform better?
CREATE NONCLUSTERED INDEX [IX_p2p] ON [dbo].[clicks]
(
[domainId],
[clickedOn] ASC
)
Or This?
CREATE NONCLUSTERED INDEX [IX_p2p] ON [dbo].[clicks]
(
[clickedOn] ASC,
[domainId]
)
The first index is clearly better than the second one for this query.
In the first case it can seek into the exact domainid
and then read the first 500 rows, which are already in clickedOn
order, and then stop (plus 500 lookups to get the other column values if the table has more than the two columns shown).
The second index might be useful for the query but only in very limited circumstances. It avoids the need to sort by clickedOn
but does require scanning the index in order and stopping after the first 500 rows matching the domainId
are found. If you are very lucky then the first 500 rows in clickedOn
order also match the domainId
predicate so it too only has to read 500 rows. But chances are this won't be the case. In the worst case there aren't even 500 matching rows to be found and it needs to read the whole index. It too needs to do the 500 lookups to get the other column values.
If the table is relatively small then neither index may be used as SQL Server may decide scanning a covering index and sorting is cheaper than the 500 lookups.