csmba (csmba@nowhere.com) writes:
[quoted text, click to view] > Hi all. I got the next very simple and strange problem. When running the
> following 2 slqs, one runs very fast, and one very slow. I looked at my
> indexes time and time again, and cannot figure out why. The table has
> about 8 million rows.
>
> Very fast:
>
> Select top 1 keyA from tableA where fieldB = 0 and keyA=keyA order by
> fieldC
>
> Very slow:
>
> Select top 1 keyA from tableA where fieldB = 0 order by fieldC
>
> Properties:
>
> keyA: integer unique key of tableA (clustered index)
>
> fieldB: integer (non-clustered index)
>
> fieldC: integer (non-clustered index)
So the optimizer need to decide: use index B to find all rows with
field B and sort these? Or traverse the index on fieldC, and perform
a bookmark lookup until a row with field B is found?
If there are many rows with fieldB = 0, the latter strategy is better.
If there are few rows, the first is better.
Of course, with an index on (fieldB, fieldC), the optimizer gets a
free ride.
--
Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/prodtechnol/sql/2005/downloads/books.mspx Books Online for SQL Server 2000 at