how to select first N rows from a table in T-SQL?

前端 未结 7 882
耶瑟儿~
耶瑟儿~ 2020-12-10 10:54

Is there any way to select, for example, first 10 rows of a table in T-SQL (working MSSQL)?
I think I saw something in Oracle defined as rownum meta variable, used in a

相关标签:
7条回答
  • 2020-12-10 11:25

    Try this:

    SELECT * FROM USERS LIMIT 10;
    
    0 讨论(0)
  • 2020-12-10 11:28

    SELECT TOP 10 * FROM TABLE_NAME ORDER BY ORDERED_UNIQUE_COLUMN DESC

    ORDERED_UNIQUE_COLUMN could be your incrementing primary key or a timestamp

    0 讨论(0)
  • 2020-12-10 11:30

    You can use Microsoft's row_number() function to decide which rows to return. That means that you aren't limited to just the top X results, you can take pages.

    SELECT * 
    FROM (SELECT row_number() over (order by UserID) AS line_no, * 
          FROM dbo.User) as users
    WHERE users.line_no < 10
    OR users.line_no BETWEEN 34 and 67
    

    You have to nest the original query though, because otherwise you'll get an error message telling you that you can't do what you want to in the way you probably should be able to in an ideal world.

    Msg 4108, Level 15, State 1, Line 3
    Windowed functions can only appear in the SELECT or ORDER BY clauses.
    
    0 讨论(0)
  • 2020-12-10 11:32
    select top(@count) * from users
    

    If @count is a constant, you can drop the parentheses:

    select top 42 * from users
    

    (the latter works on SQL Server 2000 too, while the former requires at least 2005)

    0 讨论(0)
  • 2020-12-10 11:33
    SELECT TOP 10 *
    FROM Users
    

    Note that if you don't specify an ORDER BY clause then any 10 rows could be returned, because "first 10 rows" doesn't really mean anything until you tell the database what ordering to use.

    0 讨论(0)
  • 2020-12-10 11:38

    You can also use rowcount, but TOP is probably better and cleaner, hence the upvote for Mehrdad

    SET ROWCOUNT 10
    SELECT * FROM dbo.Orders
    WHERE EmployeeID = 5
    ORDER BY OrderDate
    
    SET ROWCOUNT 0
    
    0 讨论(0)
提交回复
热议问题