Just got a small question. When trying to get a single max-Value of a table. Which one is better?
SELECT MAX(id) FROM myTable WHERE (whatever)
or
SELECT TOP 1 id FROM myTable WHERE (whatever) ORDER BY id DESC
I’m using Microsoft SQL Server 2012
There will be no difference as you can test yourself by inspecting the execution plans. If
idis the clustered index, you should see an ordered clustered index scan; if it is not indexed, you’ll still see either a table scan or a clustered index scan, but it won’t be ordered in either case.The
TOP 1approach can be useful if you want to pull along other values from the row, which is easier than pulling the max in a subquery and then joining. If you want other values from the row, you need to dictate how to deal with ties in both cases.Having said that, there are some scenarios where the plan can be different, so it is important to test depending on whether the column is indexed and whether or not it is monotonically increasing. I created a simple table and inserted 50000 rows:
On my system this created values in a/c from 1 to 50000, b/d between 3 and 9994, e/g from 2010-01-01 through 2011-05-16, and f/h from 2009-04-28 through 2012-01-01.
First, let’s compare the indexed monotonically increasing integer columns, a and c. a has a clustered index, c does not:
Results:
The big problem with the 4th query is that, unlike
MAX, it requires a sort. Here is 3 compared to 4:This will be a common problem across all of these query variations: a
MAXagainst an unindexed column will be able to piggy-back on the clustered index scan and perform a stream aggregate, whileTOP 1needs to perform a sort which is going to be more expensive.I did test and saw the exact same results across testing b+d, e+g, and f+h.
So it seems to me that, in addition to producing more standards-compliance code, there is a potential performance benefit to using
MAXin favor ofTOP 1depending on the underlying table and indexes (which can change after you’ve put your code in production). So I would say that, without further information,MAXis preferable.(And as I said before,
TOP 1might really be the behavior you’re after, if you’re pulling additional columns. You’ll want to testMAX+JOINmethods as well if that’s what you’re after.)