How to skip the first n rows in sql query

前端 未结 11 1010
清歌不尽
清歌不尽 2020-12-09 01:40

I want to fire a Query \"SELECT * FROM TABLE\" but select only from row N+1. Any idea on how to do this?

11条回答
  •  难免孤独
    2020-12-09 02:24

    I know it's quite late now to answer the query. But I have a little different solution than the others which I believe has better performance because no comparisons are performed in the SQL query only sorting is done. You can see its considerable performance improvement basically when value of SKIP is LARGE enough.

    1. Best performance but only for SQL Server 2012 and above. Originally from @Majid Basirati's answer which is worth mentioning again.

      DECLARE @Skip INT = 2, @Take INT = 2
      
      SELECT * FROM TABLE_NAME
      ORDER BY ID ASC
      OFFSET (@Skip) ROWS FETCH NEXT (@Take) ROWS ONLY
      
    2. Not as Good as the first one but compatible with SQL Server 2005 and above.

      DECLARE @Skip INT = 2, @Take INT = 2
      
      SELECT * FROM 
      (
          SELECT TOP (@Take) * FROM 
          (
              SELECT TOP (@Take + @Skip) * FROM TABLE_NAME
              ORDER BY ID ASC
          ) T1
          ORDER BY ID DESC
      ) T2
      ORDER BY ID ASC
      

提交回复
热议问题