Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Diff between Top 1 1 and Select 1 in SQL Select Query

Tags:

sql

sql-server

I have a general doubt in sql. What is actually "Top 1 1" will do ? What is the meaning of the below query ?

select top 1 1 from Worker W where not exists (select 1 from Manager M where M.Id = W.Id)

what is the diff between select "TOP 1 1" and "SELECT 1" in sql server query ?

like image 743
James Avatar asked Oct 14 '13 11:10

James


People also ask

What is the difference between top1 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. In your case, it is looking for the first ( TOP 1 ) worker that does not have a manager.

What does select top 1 mean 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).

Why do we use top 1 in SQL?

SQL TOP, LIMIT, FETCH FIRST or ROWNUM Clause The SELECT TOP clause is used to specify the number of records to return. The SELECT TOP clause is useful on large tables with thousands of records. Returning a large number of records can impact performance. Note: Not all database systems support the SELECT TOP clause.

What does 1 1 Mean SQL query?

It is a common statement that is used to return all the records from a given table. The statement where 1=1 in SQL means true. It is the same operation as running the select statement without the where clause. You might ask, what is the purpose of the clause where 1=1?


3 Answers

SELECT TOP 1 Means Selecting the very 1st record in the result set

SELECT 1 Means return 1 as the result set

SELECT TOP 1 1 FROM [SomeTable] WHERE <SomeCondition> Means if the condition is true and any rows are returned from the select, only return top 1 row and only return integer 1 for the row (no data just the integer 1 is returned).

like image 180
M.Ali Avatar answered Oct 17 '22 14:10

M.Ali


In the following, the first "1", which is part of the "TOP 1" means to stop after it gets to a single result. The second "1" is just because the author really does not care what the result is.

SELECT TOP 1 1 FROM WORKER

is essentially the same as

SELECT TOP 1 * FROM WORKER

The only question is whether it would be more efficient in the "EXISTS" part of the query than just

SELECT 1 FROM Manager...
like image 42
RPh_Coder Avatar answered Oct 17 '22 15:10

RPh_Coder


The request finds if there is at least one worker (top 1) with no manager. The SELECT 1 clause acts as a "return true".

If there is a manager, the request select 1 from Manager M where M.Id = W.Id returns 1. If there is no manager, the request returns NULL.

like image 4
Rom Eh Avatar answered Oct 17 '22 14:10

Rom Eh