What does TOP 1 mean in an sql query?

前端 未结 6 1880
情书的邮戳
情书的邮戳 2021-01-14 03:37

What does TOP 1 mean in an sql query?

SELECT TOP 1 RequestId 
FROM PublisherRequests
相关标签:
6条回答
  • 2021-01-14 03:59

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

    0 讨论(0)
  • 2021-01-14 04:00

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

    SQL Server Books Online 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.

    0 讨论(0)
  • 2021-01-14 04:01

    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

    0 讨论(0)
  • 2021-01-14 04:02

    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.

    0 讨论(0)
  • 2021-01-14 04:07

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

    0 讨论(0)
  • 2021-01-14 04:10

    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

    0 讨论(0)
提交回复
热议问题