MAX vs Top 1 - which is better?
I had to review some code, and came across something that someone did, and can't think of a reason why my way is better and it probably isn't, so, which is better/safer/more efficient?
SELECT MAX(a_date) FROM a_table WHERE a_primary_key = 5 GROUP BY event_id
OR
SELECT TOP 1 a_date FROM a_table WHERE a_primary_key = 5 ORDER BY a_date
I would have gone with the 2nd option, but I'm not sure why, and if that's right.
Solution 1:
1) When there is a clustered index on the table and the column to be queried, both the MAX()
operator and the query SELECT TOP 1
will have almost identical performance.
2) When there is no clustered index on the table and the column to be queried, the MAX()
operator offers the better performance.
Reference: http://www.johnsansom.com/performance-comparison-of-select-top-1-verses-max/
Solution 2:
Performance is generally similar, if your table is indexed.
Worth considering though: Top
usually only makes sense if you're ordering your results (otherwise, top
of what?)
Ordering a result requires more processing.
Min doesn't always require ordering. (Just depends, but often you don't need order by or group by, etc.)
In your two examples, I'd expect speed / x-plan to be very similar. You can always turn to your stats to make sure, but I doubt the difference would be significant.