How do I select last 5 rows in a table without sorting?

前端 未结 22 1205
-上瘾入骨i
-上瘾入骨i 2020-11-30 04:37

I want to select the last 5 records from a table in SQL Server without arranging the table in ascending or descending order.

相关标签:
22条回答
  • 2020-11-30 05:31

    You can retrieve them from memory.
    So first you get the rows in a DataSet, and then get the last 5 out of the DataSet.

    0 讨论(0)
  • 2020-11-30 05:31

    In SQL Server, it does not seem possible without using ordering in the query. This is what I have used.

    SELECT *
    FROM
    (
        SELECT TOP 5 *
        FROM [MyTable]
        ORDER BY Id DESC /*Primary Key*/
    ) AS T
    ORDER BY T.Id ASC; /*Primary Key*/
    
    0 讨论(0)
  • 2020-11-30 05:33

    Try this, if you don't have a primary key or identical column:

    select [Stu_Id],[Student_Name] ,[City] ,[Registered], 
           RowNum = row_number() OVER (ORDER BY (SELECT 0))    
    from student
    ORDER BY RowNum desc 
    
    0 讨论(0)
  • 2020-11-30 05:35

    Without an order, this is impossible. What defines the "bottom"? The following will select 5 rows according to how they are stored in the database.

    SELECT TOP 5 * FROM [TableName]

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