SQL Server: Why do these queries return different result sets?

China☆狼群 提交于 2019-12-24 08:26:29

问题


Query 1 = select top 5 i.item_id from ITEMS i

Query 2 = select top 5 i.item_id, i.category_id from ITEMS i

Even if I remove the top 5 clause they still return different rows.

if I run "select top 5 i.* from ITEMS i" this returns a completely different result set !!


回答1:


Because the results of a "TOP N" qualified SELECT are indeterminate if you do not have an ORDER BY clause.




回答2:


Without an ORDER BY clause, you cannot predict what order you will get results. There is probably an interesting underlying reason for why SQL Server processes those queries differently, but from a user's perspective the solution is simply to impose the ORDER BY clause that's relevant to your query, thus guaranteeing you'll know which five items come first.




回答3:


Since you're not specifying an ORDER BY clause, the optimizer will determine the most efficient way to do the query you're asking to do. This means there might be a different indexing done for the two columns you've indicated in your two queries, which results in what you're seeing.




回答4:


The reason is simple: you did not specify an ORDER BY clause. So, for example, the optimizer could choose to use different indexes to satisfy two different queries, if there is a lean index that contains ItemID but not CategoryID it can be touched to satisfy the first query. A very common question, has a canned naswer:

Without ORDER BY, there is no default sort order.



来源:https://stackoverflow.com/questions/1261625/sql-server-why-do-these-queries-return-different-result-sets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!