SQL Server TOP keyword returns different results

大憨熊 提交于 2021-02-16 18:24:19

问题


I have a T-SQL query to a table where I need the top row returned. In MySQL, this is working as expected, but in SQL Server, I am getting a different data returned which is quite puzzling.

I have attached three screen shots: 1 of the table design, 1 of the data returned when only viewing top 10 rows and 1 of the data returned when viewing the top 1000 rows. You will notice the very top row contains different information for the name column between the two queries.

The only difference in the query being the count value of the TOP keyword. This table has a total of 7 rows of data. The result with Top 1000 contains the correct ordering of rows returned. What's going on here?

Why does SQL Server change the order of rows returned depending the count value of the TOP keyword? Can anyone explain or provide a way to keep this consistent regardless of how many rows are being returned?


回答1:


Order by is not guaranteed to give same result for equal values as SQL tables represent unordered sets. And since your width is same hence you are getting different result.

To get the unique result or to make your sorting stable you need to add a column name like itemNumber to your order by clause.




回答2:


There is no difference or issue in the output. You are ordering by width and first 2 widths are same and you don't have any sub ordering so it leaves the decision up to the RDBMS (its query optimizer specifically) to present whichever first

You should also add itemNumber to your ORDER BY clause after Width

ORDER BY Width, itemNumber



回答3:


To add some context in this question, what I was trying to achieve is consistency between MySQL and MSSQL in the ordering of rows returned. I am converting a project that used MySQL over to MSSQL and this produced a problem for me. The solution to get what I want was to use Set Rowcount 1 to limit the number of rows returned. This produced 1 row of data which was ordered the same way as MySQL does.



来源:https://stackoverflow.com/questions/34408600/sql-server-top-keyword-returns-different-results

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