Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The faster of two SQL queries, sort and select top 1, or select MAX

Tags:

sql

sql-server

Which one is faster of the following two queries?

1

SELECT TOP 1 order_date
FROM         orders WITH (NOLOCK)
WHERE customer_id = 9999999
ORDER BY order_date DESC

2

SELECT MAX(order_date)
FROM         orders WITH (NOLOCK)
WHERE customer_id = 9999999
like image 287
Ron Avatar asked Jan 28 '10 21:01

Ron


People also ask

Which query is faster in SQL?

Use CASE instead of UPDATE UPDATE statement takes longer than CASE statement due to logging. On the other hand, CASE statement determines what needs to be updated and makes your SQL queries faster.

What helps speed up select queries and where clause?

Indexing makes columns faster to query by creating pointers to where data is stored within a database.

Why do queries run faster the second time?

When you run your query for the first time and the data is not in cache, the server read the data from disk. It is time-comsuming. The second time you execute the same query data is already in cache so it requires less time.


2 Answers

With an index on order_date, they are of same performance.

Without an index, MAX is a little bit faster, since it will use Stream Aggregation rather than Top N Sort.

like image 196
Quassnoi Avatar answered Oct 05 '22 22:10

Quassnoi


ORDER BY is almost always slowest. The table's data must be sorted.

Aggregate functions shouldn't slow things down as much as a sort.

However, some aggregate functions use a sort as part of their implementation. So a particular set of tables in a particular database product must be tested experimentally to see which is faster -- for that set of data.

like image 28
S.Lott Avatar answered Oct 05 '22 23:10

S.Lott