How to skip the first n rows in sql query

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

    In order to do this in SQL Server, you must order the query by a column, so you can specify the rows you want.

    Example:

    select * from table order by [some_column] 
    offset 10 rows
    FETCH NEXT 10 rows only
    
    0 讨论(0)
  • 2020-12-09 02:07

    SQL Server:

    select * from table
    except
    select top N * from table
    

    Oracle up to 11.2:

    select * from table
    minus
    select * from table where rownum <= N
    
    with TableWithNum as (
        select t.*, rownum as Num
        from Table t
    )
    select * from TableWithNum where Num > N
    

    Oracle 12.1 and later (following standard ANSI SQL)

    select *
    from table
    order by some_column 
    offset x rows
    fetch first y rows only
    

    They may meet your needs more or less.

    There is no direct way to do what you want by SQL. However, it is not a design flaw, in my opinion.

    SQL is not supposed to be used like this.

    In relational databases, a table represents a relation, which is a set by definition. A set contains unordered elements.

    Also, don't rely on the physical order of the records. The row order is not guaranteed by the RDBMS.

    If the ordering of the records is important, you'd better add a column such as `Num' to the table, and use the following query. This is more natural.

    select * 
    from Table 
    where Num > N
    order by Num
    
    0 讨论(0)
  • 2020-12-09 02:13

    Query: in sql-server

    DECLARE @N INT = 5 --Any random number
    
    SELECT * FROM (
            SELECT ROW_NUMBER() OVER(ORDER BY ID) AS RoNum
                  , ID --Add any fields needed here (or replace ID by *)
            FROM TABLE_NAME
    ) AS tbl 
    WHERE @N < RoNum
    ORDER BY tbl.ID
    

    This will give rows of Table, where rownumber is starting from @N + 1.

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

    try below query it's work

    SELECT * FROM `my_table` WHERE id != (SELECT id From my_table LIMIT 1)
    

    Hope this will help

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

    What about:

    SELECT * FROM table LIMIT 50 OFFSET 1
    
    0 讨论(0)
  • 2020-12-09 02:18

    In Faircom SQL (which is a pseudo MySQL), i can do this in a super simple SQL Statement, just as follows:

    SELECT SKIP 10 * FROM TABLE ORDER BY Id
    

    Obviously you can just replace 10 with any declared variable of your desire.

    I don't have access to MS SQL or other platforms, but I'll be really surprised MS SQL doesn't support something like this.

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