Using ORDER BY on indexed columns
In SQL Server 2008, let's say I have an index (LastName, FirstName) on the table Employees. The index is sorted ASC on both columns. Is there any point to the ORDER BY in the following query?
SELECT LastName, FirstName
FROM Employees
ORDER BY LastName, FirstName
Is the query analyzer smart enough to omit the ORDER BY since the data is already ordered per the indexes? Or is it safer to always specify the desired ordering?
Ps. I'm not trying to get into "micro-optimizations" - just a better understanding of what 开发者_Go百科happens in this scenario.
More Info:
To test the theory, I added some data randomly, created a query that omitted the ORDER BY, and the results were ordered.
NO, you cannot omit the order by.
There is no guarantee of the order in which records return if it is not specifically ordered.
Have a look at
Order of Result Set of SELECT Statement on Clustered Indexed Table When ORDER BY is Not Used
Even you must use ORDER BY clause to get the result rodered but SQL optimizer is smart enough to utilize the index for this operation. Check the execution plan and you would find that only the index is used and not the base table and the operation would also not take much time as the records are fetched from index where they are already placed ordered.
Just wanted to mention one of the comments from the article listed in astander's answer, which I found really interesting...
Create view foobar
as
select top 100 percent * from foo order by bar
select * from foobar
The above statement will not be a sorted resultset from foo. You did not ASK for an order, so the query plan can actually drop the order request from the view. Even if this DID work on some older Versions of SQL Server, it is not an expected result. You didn't ask for an order in your final query, that means there is no need to order the result before returning it to you…
精彩评论