How do I limit the number of rows returned by an Oracle query after ordering?

前端 未结 17 1481
夕颜
夕颜 2020-11-21 04:56

Is there a way to make an Oracle query behave like it contains a MySQL limit clause?

In MySQL, I can do this:

         


        
17条回答
  •  情书的邮戳
    2020-11-21 05:19

    Pagination queries with ordering are really tricky in Oracle.

    Oracle provides a ROWNUM pseudocolumn that returns a number indicating the order in which the database selects the row from a table or set of joined views.

    ROWNUM is a pseudocolumn that gets many people into trouble. A ROWNUM value is not permanently assigned to a row (this is a common misunderstanding). It may be confusing when a ROWNUM value is actually assigned. A ROWNUM value is assigned to a row after it passes filter predicates of the query but before query aggregation or sorting.

    What is more, a ROWNUM value is incremented only after it is assigned.

    This is why the followin query returns no rows:

     select * 
     from (select *
           from some_table
           order by some_column)
     where ROWNUM <= 4 and ROWNUM > 1; 
    

    The first row of the query result does not pass ROWNUM > 1 predicate, so ROWNUM does not increment to 2. For this reason, no ROWNUM value gets greater than 1, consequently, the query returns no rows.

    Correctly defined query should look like this:

    select *
    from (select *, ROWNUM rnum
          from (select *
                from skijump_results
                order by points)
          where ROWNUM <= 4)
    where rnum > 1; 
    

    Find out more about pagination queries in my articles on Vertabelo blog:

    • Oracle ROWNUM Explained
    • Top-N and pagination queries

提交回复
热议问题