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
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%.