patternsqlMajor
How does SQL Server order results when joins are used?
Viewed 0 times
ordersqlareuseddoeshowserverresultswhenjoins
Problem
How does SQL Server figure out the order of the records in the result set of query execution?
I am trying to make heads or tails of it but find myself scratching my head. When I change the fields I am selecting the order also changes. When I execute the below SQL with a
I am trying to make heads or tails of it but find myself scratching my head. When I change the fields I am selecting the order also changes. When I execute the below SQL with a
SELECT * I get the same records but in a much different order.SELECT TOP (900)
AD.ATTACHMENTID,
AD.NAME,
AD.ISINLINE,
AD.INSERTEDDATETIME,
ATMT.ATTACHMENTBLOB,
U.UFID
FROM ATTACHMENTDETAIL AD WITH (NOLOCK)
INNER JOIN MESSAGEATTACHMENT MA ON MA.ATTACHMENTID = AD.ATTACHMENTID
INNER JOIN ATTACHMENT ATMT ON ATMT.ATTACHMENTID = AD.ATTACHMENTID
INNER JOIN MESSAGE MSG ON MSG.ID = MA.MESSAGEID
INNER JOIN MESSAGEDETAIL MD ON MD.MESSAGEID = MA.MESSAGEID
INNER JOIN [USER] U ON U.ID = MD.USERID
LEFT OUTER JOIN XmlExtractionMapping XM ON MA.MESSAGEID = XM.MessageId
WHERE AD.FILEBOXTOKEN IS NULL
AND (XM.XMLEXTRACTIONDATE IS NOT NULL OR
(MSG.MESSAGESOURCEID = 1 AND MD.FolderId <> -4))
AND AD.ISINLINE = 'FALSE'Solution
Since you haven't told SQL Server how to order the results, it is free to do so in whatever is the most efficient. In this way it will depend on what is the cheapest to sort, and the columns you select will drive that because it in turn depends on the cheapest index(es) to use to get at the information requested by the query. This can change from execution to execution not just by changing the query text but also by things like data changes, statistics updates, freeproccache, service packs, hotfixes, etc. This is especially volatile with so many tables involved if the underlying data is changing rapidly, as it tends to do in OLTP applications.
If you want a predictable order, why don't you use
Even though, in a lot of cases, you see the same order over and over again for the same query, there is no guarantee unless you say
If you want a predictable order, why don't you use
ORDER BY on the query? As written, the SQL specifies that any 900 rows are acceptable, in any order.Even though, in a lot of cases, you see the same order over and over again for the same query, there is no guarantee unless you say
ORDER BY .Context
StackExchange Database Administrators Q#29381, answer score: 21
Revisions (0)
No revisions yet.