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/mo
For the queries to have the same result you would need:
SELECT MAX(a_date) FROM a_table WHERE a_primary_key = 5
SELECT TOP 1 a_date FROM a_table WHERE a_primary_key = 5 ORDER BY a_date DESC
The best way to know which is faster is to check the query plan and do your benchmarks. There are many factors that would affect the speed, such as table/heap size, etc. And even different versions of the same database may be optimized to favor one query over the other.
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/
I ran an experiment and I got the Clustered Index Cost 98% when I used an aggregate like Min/ Max, but when I used TOP and Order By, Clustered Index Scan cost was reduced to 45%. When it comes to querying large datasets, TOP and Order By combination will be less expensive and will give faster results.
They are different queries.
The first one returns many records (the biggest a_date
for each event_id
found within a_primary_key = 5
)
The second one returns one record (the smallest a_date
found within a_primary_key = 5
).
I perform max and top on one table with 20,00,000+ records , and found that Top give faster result with order by than max or min function.
So , best way is to execute both your query one by one for some time and check connection elapsed time for than.
MAX
and TOP
function differently. Your first query will return the maximum value found for a_date
that has a a_primary_key = 5
for each different event_id
found. The second query will simply grab the first a_date
with a a_primary_key = 5
found in the result set.