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

前端 未结 22 1204
-上瘾入骨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:23

    There is a handy trick that works in some databases for ordering in database order,

    SELECT * FROM TableName ORDER BY true

    Apparently, this can work in conjunction with any of the other suggestions posted here to leave the results in "order they came out of the database" order, which in some databases, is the order they were last modified in.

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

    Well, the "last five rows" are actually the last five rows depending on your clustered index. Your clustered index, by definition, is the way that he rows are ordered. So you really can't get the "last five rows" without some order. You can, however, get the last five rows as it pertains to the clustered index.

    SELECT TOP 5 * FROM MyTable
    ORDER BY MyCLusteredIndexColumn1, MyCLusteredIndexColumnq, ..., MyCLusteredIndexColumnN DESC
    
    0 讨论(0)
  • 2020-11-30 05:25
    select * 
    from table 
    order by empno(primary key) desc 
    fetch first 5 rows only
    
    0 讨论(0)
  • 2020-11-30 05:26
    1. You need to count number of rows inside table ( say we have 12 rows )
    2. then subtract 5 rows from them ( we are now in 7 )
    3. select * where index_column > 7

      select * from users
      where user_id > 
      ( (select COUNT(*) from users) - 5)
      

      you can order them ASC or DESC

      But when using this code

      select TOP 5 from users order by user_id DESC
      

      it will not be ordered easily.

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

    Get the count of that table

    select count(*) from TABLE
    select top count * from TABLE where 'primary key row' NOT IN (select top (count-5) 'primary key row' from TABLE)
    
    0 讨论(0)
  • 2020-11-30 05:31

    Search 5 records from last records you can use this,

    SELECT *
    FROM   Table Name
    WHERE  ID <= IDENT_CURRENT('Table Name')
    AND ID >= IDENT_CURRENT('Table Name') - 5
    
    0 讨论(0)
提交回复
热议问题