SQL 如果未指定“Order by”,查询会为您的记录集选择什么顺序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20050341/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
When no 'Order by' is specified, what order does a query choose for your record set?
提问by dmoney
I was always of the impression that a query with no specified 'Order by' rule, would order this by the results by what was specified within your where clause.
我总是觉得一个没有指定“Order by”规则的查询会根据你的 where 子句中指定的结果来排序。
For instance, my where clause states:
例如,我的 where 子句指出:
WHERE RESULTS_I_AM_SEARCHING_FOR IN
ITEM 1
ITEM 2
ITEM 3
I would have imagined that the results returned for items 1, 2 and 3 would be in the order specified in the where, however this is not the case. Does anyone know what order it sorts them in when not specified?
我会想象为项目 1、2 和 3 返回的结果将按照 where 中指定的顺序,但事实并非如此。有谁知道它在未指定时按什么顺序对它们进行排序?
Thanks and sorry for the really basic question!
感谢并抱歉这个非常基本的问题!
Damon
达蒙
回答by marc_s
If you don't specify an ORDER BY
, then there is NO ORDERdefined.
如果您未指定ORDER BY
,则没有定义ORDER。
The results can be returned in an arbitrary order - and that might change over time, too.
结果可以以任意顺序返回 - 这也可能随着时间的推移而改变。
There is no "natural order" or anything like that in a relational database (at least in all that I know of). The only way to get a reliable ordering is by explicitlyspecifying an ORDER BY
clause.
关系数据库中没有“自然顺序”或类似的东西(至少在我所知道的所有内容中)。获得可靠排序的唯一方法是明确指定ORDER BY
子句。
Update:for those who still don't believe me - here's two excellent blog posts that illustrate this point (with code samples!) :
更新:对于那些仍然不相信我的人 - 这里有两篇出色的博客文章可以说明这一点(带有代码示例!):
- Conor Cunningham (Architect on the Core SQL Server Engine team): No Seatbelt - Expecting Order without ORDER BY. Page seems to have moved so check wayback machine.
- Alexander Kuznetsov: Without ORDER BY, there is no default sort order
- Conor Cunningham(核心 SQL Server 引擎团队的架构师):没有安全带 - 没有 ORDER BY 期待订单。页面似乎已移动,因此请检查回程机。
- Alexander Kuznetsov:没有 ORDER BY,就没有默认的排序顺序
回答by Curt
With SQL Server, if no ORDER BY
is specified, the results are returned in the quickest way possible.
对于 SQL Server,如果ORDER BY
指定no ,则以最快的方式返回结果。
Therefore without an ORDER BY
, make no assumptions about the order.
因此,如果没有ORDER BY
,则不对订单做任何假设。
回答by Curt
As it was already said you should never rely on the "default order" because it doesn't exist. Anyway if you still want to know some curious details about sql server implementation you can check this out:
正如已经说过的那样,您永远不应该依赖“默认顺序”,因为它不存在。不管怎样,如果你仍然想知道一些关于 sql server 实现的奇怪细节,你可以看看这个:
http://exacthelp.blogspot.co.uk/2012/10/default-order-of-select-statement-in.html
http://exacthelp.blogspot.co.uk/2012/10/default-order-of-select-statement-in.html