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

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

提交回复
热议问题