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 queries would run faster or gives better performance.
Id
is the primary key and autoincrement
field for Table1
. And this is for Sql Server 2005.
SELECT MAX(Id) FROM Table1
SELECT TOP 1 Id FROM Table1 ORDER BY Id DESC
[Edit]
Yes in this case Id
is the field on which I have defined the clustered index.
If the index is ID DESC
then what..
And yes it would be nice to know how the performance would be affected if
1. Id is a clustered index + primary key.
2. Id is a clustered index and not primary key.
3. Id is a non clustered index ASC + primary key.
4. Id is a non clustered index ASC and not primary key.
5. Id is a non clustered index DESC + primary key.
6. Id is a non clustered index DESC and not primary key.
7. Id is just AutoIncrement
Hope its not a tall order!
Nobody mentioned IDENT_CURRENT('Table1') - blows them all away - of course it only works on identity columns, but that was the question...
If there is a clustered index there is virtually no difference in performance between the two queries.
This is becuase both will perform a Clustered Index Scan that will bear 100% of the query cost.
Performing the two queries on a column that does not have an index results in 3 operators being used in both execution plans.
The Top clause uses the Sort operator and the Max function uses a Stream Aggregate operator.
When there is no index, the MAX() function provides better performance.
Proof of concept can be found and full walkthrough of a test scenario can be found here:
Performance Comparison Top 1 Verses MAX() Function
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With