Performance difference: select top 1 order by vs. select min(val)

巧了我就是萌 提交于 2019-12-21 17:25:09

问题


Question is simple. Which query will be faster:

SELECT TOP 1 value FROM table ORDER BY value

or

SELECT TOP 1  MIN(value) FROM table

We can assume that we have two cases, Case 1. No index and Case 2. With index on value.
Any insights are appreciated. Thanks!


回答1:


In the case where no index exists:

  • MIN(value) should be implemented in O(N) time with a single scan;
  • TOP 1 ... ORDER BY will require O(N Log N) time because of the specified sort (unless the DB engine is smart enough to read intent, which I would hate to rely on in production code).

When an index does exist:

  • Both should require only O(1) time, using the index.


来源:https://stackoverflow.com/questions/15275968/performance-difference-select-top-1-order-by-vs-select-minval

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