Does the DBMS have to do this, to run this query, the exact way I describe it above? No, of course not and you know that. It may not read the table but read from an index. Or it may use two indexes if it thinks it's better (faster). Or three. Or it may use a cached result (not SQL Server but other DBMS cache query results). Or it may use parallel execution one time and not the next time it runs. Or ... (add any other feature that affects execution and execution plans).
But isn't using the clustered index the best/fastest way to get results?
- No, not always. It most probably ismight be the first time you run the query. The second time, it may use thea cached result (if the DBMS has such a feature, not SQL Server*). The 1000th time the result may have been removed from the cache and another result may exist there. Say, you had executed this query just before:
- And the cached result (from the above query) is another, different one that still matches your conditions but is not the first in your (wanted) ordering. And you have told the DBMS not to care about the order.
and the cached result (from the above query) is another, different one that still matches your conditions but is not the first in your (wanted) ordering. And you have told the DBMS not to care about the order.
OK, so only cache can affect this?
- No, probably many other things, too. Like other indexes that could be considered (at that time) by the DBMS as better for this query. Like if some future developer changes or completely removes this clustered index you have. Like if you or some other developer adds another clustered index (SQL-Server does not have such feature now but it may have in the future or you move to another DBMS). Like if you updated and the new optimizer has a minor bug.
- other indexes were considered, at that time by the DBMS as better for this query.
- a developer changed or completely removed this clustered index you had.
- you or some other developer added another index that the optimizer decided it's more efficient to use than the CI.
- you updated to a new version and the new optimizer has a minor bug or a change in how it ranks and chooses execution plans.
- statistics were updated.
- parallel execution was chosen instead.
*: SQL Server does not cache query results but the Enterprise Edition does have an Advanced Scanning feature which is kind of similar in that you may get different results because of concurrent queries. Not sure exactly when this kicks in though. (thnx @Martin Smith for the tip.)
I hope you are convinced that you should never rely that an SQL query will return results in a specific order, unless you specify so. AmdAnd never use TOP (n)
without ORDER BY
, unless of course you just want onen rows in the result and you don't care which one isones are returned.