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!
In theory, they will use same plans and run almost same time.
In practice,
will more probably use a
PRIMARY KEY INDEX.Also, this one is more extendable if you will decide to select some else column along with
id.An actual plan on
MAX()says:, while plan for
TOP 1says:, i. e.
aggregateis omitted.Aggregate actually won’t do anything here, as there is but one row.
P. S. As
@Mehrdad Afshariand@John Sansomnoted, on a non-indexed fieldMAXis slightly faster (of course not20times as optimizer says):