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

后端 未结 7 1249
甜味超标
甜味超标 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:53

    MAX is generally faster.

    Both queries will use the index on the column if exists.

    If no index exists on the column, the TOP 1 query will use a Top N Sort operator to sort the table instead of stream aggregation, which makes it slower.

    MAX also provides better readability.

    Side Note: while MAX will use a stream aggregate operator in the execution plan in the indexed case, it doesn't have any specific cost as it's just processing a single row (Actual Rows = 1). You can compare queries by running them in a single batch and see the relative cost. In the indexed case, both queries will cost 50%. I tested the non-indexed case on a table with about 7000 rows and TOP will cost 65% in comparison to MAX that costs 35%.

    0 讨论(0)
提交回复
热议问题