MAX vs Top 1 - which is better?

前端 未结 7 1787
慢半拍i
慢半拍i 2020-12-03 02:35

I had to review some code, and came across something that someone did, and can\'t think of a reason why my way is better and it probably isn\'t, so, which is better/safer/mo

7条回答
  •  一整个雨季
    2020-12-03 03:01

    For the queries to have the same result you would need:

    SELECT MAX(a_date) FROM a_table WHERE a_primary_key = 5
    
    SELECT TOP 1 a_date FROM a_table WHERE a_primary_key = 5 ORDER BY a_date DESC
    

    The best way to know which is faster is to check the query plan and do your benchmarks. There are many factors that would affect the speed, such as table/heap size, etc. And even different versions of the same database may be optimized to favor one query over the other.

提交回复
热议问题