tags:

views:

638

answers:

8

What does TOP 1 mean in an sql query?

SELECT TOP 1 RequestId 
FROM PublisherRequests
+10  A: 

It will select the first row from the PublisherRequests table.

EDIT: [The order will be defined based on the clustered key in that table - This statement is incorrect]. Actually, according to Alex's findings, and according to BOL, the order of the rows will be arbitrary.

Reference can be found here.

Kirtan
not necessarily true. I posted a repro demonstrating that this is not always the case:http://sqlblog.com/blogs/alexander_kuznetsov/archive/2009/05/20/without-order-by-there-is-no-default-sort-order.aspx
AlexKuznetsov
Also see Conor Cunningham's (MS Query Optimisation Team) blog entry on the same topichttp://blogs.msdn.com/conor_cunningham_msft/archive/2008/08/27/no-seatbelt-expecting-order-without-order-by.aspx
GilaMonster
+2  A: 

It means only return the top 1 row, i.e. the first row.

David M
A: 

Your query in specific will return the first row of the table. If you were to add a WHERE clause, it would return the first row of those results. Example:

SELECT Abbr FROM States WHERE Abbr LIKE 'T%'; -- ['TN', 'TX']
SELECT TOP 1 Abbr FROM States WHERE Abbr LIKE 'T%'; -- ['TN']
Chris Doggett
+3  A: 

The TOP can be used to return as many rows as necessary, or a percentage of the total rows included - for more information, see http://msdn.microsoft.com/en-us/library/ms189463.aspx

thecoop
+6  A: 

The query in the example will return the first RequestID from the table PublisherRequests.
The order of the results without an Order By clause is arbitrary. So, your example will return an arbitrary RequestID (i.e. the first RequestID in an arbitrarily ordered list of RequestIDs).
You can change the order by defining an Order By.
For example, to get the last entered ID, you can write

Select Top 1 RequestID
From PublisherRequests
Order By RequestID Desc

Updated to include corrected order information from @Kirtan Gor and @AlexK

a programmer
A: 

It limits the number of rows returned from the query to just 1. Its the same as Limit 1 in MySQL.

corymathews
+8  A: 

I disagree with "The order will be defined based on the clustered key in that table."

BOL is quite explicit: If the query has no ORDER BY clause, the order of the rows is arbitrary

a repro demonstrating that this is not always the case: Without ORDER BY, there is no default sort order.

AlexKuznetsov
+1. Saw the link you posted. Thanks for the info. Answer updated.
Kirtan
A: 

If you want a given number of results, you can also use the limit keyword,

i.e.

Select RequestID From PublisherRequests Order By RequestID Desc LIMIT 1
Robbie
The question is tagged SQL Server, and this is not valid syntax for SQL Server
bdukes