Oracle TOP N ordered rows

后端 未结 4 619
名媛妹妹
名媛妹妹 2020-12-07 04:15

I would like to get the top N rows from an Oracle table sorted by date.

The common way to do this, and this solution returns for every question I could find on SO/go

4条回答
  •  情书的邮戳
    2020-12-07 05:05

    Question is, is there a way to limit the number of ORDERED rows returned in the subquery ?

    The following is what I typically use for top-n type queries (pagination query in this case):

    select * from (
      select a.*, rownum r
      from (
        select *
        from your_table
        where ...
        order by ...
      ) a
      where rownum <= :upperBound
    )
    where r >= :lowerBound;
    

    I usually use an indexed column to sort in inner query, and the use of rownum means Oracle can use the count(stopkey) optimization. So, not necessarily going to do full table scan:

    create table t3 as select * from all_objects;
    alter table t3 add constraint t_pk primary key(object_id);
    analyze table t3 compute statistics;
    
    delete from plan_table;
    commit;
    explain plan for
    select * from (
      select a.*, rownum r
      from (
        select object_id, object_name
        from t3
        order by object_id
      ) a
      where rownum <= 2000
    )
    where r >= 1;
    
    select operation, options, object_name, id, parent_id, position, cost, cardinality, other_tag, optimizer
    from plan_table
    order by id;
    

    You'll find Oracle does a full index scan using t_pk. Also note the use of stopkey option.

    Hope that explains my answer ;)

提交回复
热议问题