How to skip the first n rows in sql query

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

提交回复
热议问题