How to skip the first n rows in sql query

前端 未结 11 988
清歌不尽
清歌不尽 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:20

    Do you want something like in LINQ skip 5 and take 10?

    SELECT TOP(10) * FROM MY_TABLE  
    WHERE ID not in (SELECT TOP(5) ID From My_TABLE);
    

    This approach will work in any SQL version.

    0 讨论(0)
  • 2020-12-09 02:24

    Use this:

    SELECT *
    FROM Sales.SalesOrderHeader 
    ORDER BY OrderDate
    OFFSET (@Skip) ROWS FETCH NEXT (@Take) ROWS ONLY
    

    https://stackoverflow.com/a/19669165/1883345

    0 讨论(0)
  • 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
      
    0 讨论(0)
  • 2020-12-09 02:24

    This works with all DBRM/SQL, it is standard ANSI:

    SELECT *
      FROM owner.tablename A
     WHERE condition
      AND  n+1 <= (
             SELECT COUNT(DISTINCT b.column_order)
               FROM owner.tablename B
              WHERE condition
                AND b.column_order>a.column_order
              )
    ORDER BY a.column_order DESC
    
    0 讨论(0)
  • 2020-12-09 02:27

    For SQL Server 2012 and later versions, the best method is @MajidBasirati's answer.

    I also loved @CarlosToledo's answer, it's not limited to any SQL Server version but it's missing Order By Clauses. Without them, it may return wrong results.

    For SQL Server 2008 and later I would use Common Table Expressions for better performance.

    -- This example omits first 10 records and select next 5 records
    ;WITH MyCTE(Id) as
    (
        SELECT TOP (10) Id 
        FROM MY_TABLE
        ORDER BY Id
    )
    SELECT TOP (5) * 
    FROM MY_TABLE
        INNER JOIN MyCTE ON (MyCTE.Id <> MY_TABLE.Id) 
    ORDER BY Id
    
    0 讨论(0)
提交回复
热议问题