Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance effect of using TOP 1 in a SELECT query

Tags:

I have a User table where there are a Username and Application columns. Username may repeat but combination of Username + Application is unique, but I don't have the unique constraint set on the table (for performance)

Question: will there be any difference (performance-wise) between :

SELECT * FROM User where UserName='myuser' AND Application='myapp' 

AND -

SELECT TOP 1 * FROM User where UserName='myuser' AND Application='myapp' 

As combination of Username + Application is unique, both queries will always return no more than one record, so TOP 1 doesn't affect the result. I always thought that adding TOP 1 will really speed things up as sql server would stop looking after it found one match, but I recently read in an article that using TOP will actually slow things down and it's recommended to avoid, though they haven't explained why.

Any comments?

Thank you! Andrey

like image 201
Andrey Avatar asked Sep 16 '09 20:09

Andrey


People also ask

Why is select top faster?

If you don't have an ORDER BY or a DISTINCT, SELECT TOP(1) Name FROM Worker is faster. The reason for this is that if you do happen to have an ORDER BY or a DISTINCT, the query has to go through the entire table to sort and filter out unwanted results.

How does query affect performance?

Query performance also depends on data volume and transaction concurrency. Executing the same query on a table with millions of records requires more time that performing the same operation on the same table with only thousands of records. A lot of concurrent transactions can degrade SQL Server performance.

What does select top 1 do in SQL?

The TOP 1 means to only return one record as the result set. which record is returned, depends on the column that is specified in the order by clause. If you want to find the record with the minimum value for a particular column, you would query the record with the ORDER BY being ascending (ASC).


2 Answers

You may get some performance difference from just using top, but the real performance you get by using indexes.

If you have an index for the UserName and Application fields, the database doesn't even have to touch the table until it has isolated the single record. Also, it will already know from the table statistics that the values are unique, so using top makes no difference.

like image 123
Guffa Avatar answered Sep 22 '22 23:09

Guffa


If there's more than one row in the results and no ORDER BY clause, the "TOP 1" saves a ton of work for the server. If there's an order by clause the server still has to materialize the entire result set anyway, and if there's only one row it doesn't really change anything.

like image 32
Joel Coehoorn Avatar answered Sep 23 '22 23:09

Joel Coehoorn