For autoincrement fields: MAX(ID) vs TOP 1 ID ORDER BY ID DESC

后端 未结 7 1266
甜味超标
甜味超标 2020-12-06 10:20

I want to find the highest AutoIncremented value from a field. (its not being fetched after an insert where I can use @@SCOPE_IDENTITY etc) Which of these two q

7条回答
  •  被撕碎了的回忆
    2020-12-06 10:39

    I've just tested the two SQL statements you provided against a typical dataset:

    SELECT MAX(Id) FROM Table1
    
    SELECT TOP 1 Id FROM Table1 ORDER BY Id DESC
    

    And SELECT TOP 1 Id FROM Table1 ORDER BY Id DESC is marginally faster because it has one fewer step in the execution plan. Here are the execution plans each query carries out:

    SELECT MAX(Id) FROM Table1

    Clustered Index Scan >> Top >> Stream Aggregate >> Select

    SELECT TOP 1 Id FROM Table1 ORDER BY Id DESC

    Clustered Index Scan >> Top >> Select

提交回复
热议问题