Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance difference: select top 1 order by vs. select min(val)

Question is simple. Which query will be faster:

SELECT TOP 1 value FROM table ORDER BY value

or

SELECT TOP 1  MIN(value) FROM table

We can assume that we have two cases, Case 1. No index and Case 2. With index on value.
Any insights are appreciated. Thanks!

like image 960
www Avatar asked Mar 07 '13 16:03

www


People also ask

Does order of WHERE clause affect performance?

The order in which columns appear in the WHERE clause does not affect query efficiency. Only the order of columns when defining the index matters.

What is the difference between select * and select 1?

There is no difference between EXISTS with SELECT * and SELECT 1. SQL Server generates similar execution plans in both scenarios.

Does order of select matter in SQL?

No, you can specify the 'params' (the parts of the where clause) in any order and the query optimizer will handle it.

Is Select * faster than select column?

Selecting distinct and less than all columns will always be faster than selecting *.


1 Answers

In the case where no index exists:

  • MIN(value) should be implemented in O(N) time with a single scan;
  • TOP 1 ... ORDER BY will require O(N Log N) time because of the specified sort (unless the DB engine is smart enough to read intent, which I would hate to rely on in production code).

When an index does exist:

  • Both should require only O(1) time, using the index.
like image 173
Pieter Geerkens Avatar answered Nov 09 '22 01:11

Pieter Geerkens