Sign in
SQL Server Engine Tips
Guidelines, Best Practices, TSQL and SQL Programming Tips & Tricks.
Translate This Page
Translate this page
Powered by
Microsoft® Translator
Options
Blog Home
About
Email Blog Author
Share this
RSS for posts
Atom
RSS for comments
Search
Tags
Announcements
Architecture
Best Practices
Catalog Views
Dynamic Management View
General
Oracle SQL Migration
Pages
Performance - Engine
Performance - SQL/TSQL
Performance - Tools
Performance Troubleshooting
Programming
SQL Server 2005
SQL Server 2008
Archive
Archives
July 2008
(1)
June 2008
(2)
August 2007
(1)
April 2007
(1)
March 2007
(3)
February 2007
(3)
December 2006
(1)
November 2006
(2)
September 2006
(3)
July 2006
(1)
June 2006
(3)
May 2006
(1)
February 2006
(3)
October 2005
(7)
September 2005
(3)
August 2005
(2)
July 2005
(3)
June 2005
(3)
May 2005
(2)
Ordering guarantees in SQL Server...
MSDN Blogs
>
SQL Server Engine Tips
>
Ordering guarantees in SQL Server...
Ordering guarantees in SQL Server...
Rate This
SQL Server Engine Team
20 Jul 2005 2:20 PM
Comments
18
Ordering guarantees of queries in various context is a common source of confusion. For example, a common workaround to make the results from querying a view ordered is to introduce TOP 100 PERCENT and ORDER BY in the view definition. But this however does not guarantee order in the actual results sent to the client since the query optimizer will re-order operations to find more efficient query plans. Note that even though this topic applies to SQL Server 2005 most of the rules are valid for SQL Server 2000 too.
Here are the scenarios that guarantee ordering:
If you have an ORDER BY in the top-most SELECT block in a query, the presentation order of the results honor that ORDER BY request
If you have a TOP in the same SELECT block as an ORDER BY, any TOP computation is performed with respect to that ORDER BY. For example, if there is a TOP 5 and ORDER BY clause then SQL Server picks the TOP 5 rows within a given sort. Note that this does
not
guarantee that subsequent operations will somehow retain the sort order of a previous operation. The query optimizer re-orders operations to find more efficient query plans
Cursors over queries containing ORDER BY in the top-most scope will navigate in that order
INSERT queries that use SELECT with ORDER BY to populate rows guarantees how identity values are computed but not the order in which the rows are inserted
SQL Server 2005 supports a number of new "sequence functions" like RANK(), ROW_NUMBER() that can be performed in a given order using a OVER clause with ORDER BY
For backwards compatibility reasons, SQL Server provides support for assignments of type SELECT @p = @p + 1 ... ORDER BY at the top-most scope.
--
Conor Cunningham
Query Optimizer Development Lead
18 Comments
General
,
Best Practices
Blog - Comment List MSDN TechNet
Comments
Loading...
Leave a Comment
Name
Comment
Please add 1 and 6 and type the answer here:
Post