Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Top 1 faster if only selecting one row

Tags:

sql

sql-server

Does the database break the selection loop as fast as it has got one record when using Top 1?

So that select top 1 * from customer where cusId = 1234

is faster than select * from customer where cusId = 1234 ?

cusId is unique, so does MSSql understand to do it "faster" without top 1?

like image 907
user822448 Avatar asked Jul 05 '11 11:07

user822448


People also ask

Can we use top with Group By clause?

Typically, these are accomplished using the TOP or LIMIT clause. Problem is, Top N result sets are limited to the highest values in the table, without any grouping. The GROUP BY clause can help with that, but it is limited to the single top result for each group.

What is the difference between top 1 and top 1 1 in SQL query?

SELECT TOP 1 1 will select exactly 0 or 1 1 s. SELECT 1 will select 1 exactly N rows, where N is the number of rows that match your criteria.

How do I select a single row in SQL?

To select rows using selection symbols for character or graphic data, use the LIKE keyword in a WHERE clause, and the underscore and percent sign as selection symbols. You can create multiple row conditions, and use the AND, OR, or IN keywords to connect the conditions.

How do you keep records on top when ordering data?

Answer: In Order by clause you can use a number which will indicate the ordinal position of the column name used in the select statement. For example Order by 2 means order by the second column values specified in the SELECT statement.


1 Answers

If cusId is a primary key, both should be the same re: performance.

EDIT:

You are only adding overhead with TOP 1 if you have unique index that will return 1 result anyway.

It will be different if you have order by something than you are interested in only one row.

MORE:

There is no looping involved, unless there is a table scan involved and there is no index at all for cusId. In that case, TOP 1 can't help you anyway.

like image 168
Daniel Mošmondor Avatar answered Nov 07 '22 08:11

Daniel Mošmondor