Believe in yourself, and remember that anything is possible. Believe in what makes you feel good. Believe in what makes you happy. Believe in the dreams you have always wanted to come true.

Edi Yanto (何 萬 新)

Oracle Top-N Query

Posted by: Edi Yanto on: October 1, 2009

  1. Using RANK function, with a faster execution plan (WINDOW SORT PUSHED RANK)
    SELECT Empno, Ename, Job, Mgr, Hiredate, Sal
    FROM
    (SELECT Empno, Ename, Job, Mgr, Hiredate, Sal,
    RANK() OVER
    (ORDER BY SAL Desc) AS Emp_Rank
    FROM Emp)
    WHERE Emp_Rank <= 5;
  2. Using row_number function (speed up top-n queries)
    SELECT Empno, Ename, Job, Mgr, Hiredate, Sal
    FROM
    (SELECT Empno, Ename, Job, Mgr, Hiredate, Sal,
    row_number() OVER
    (ORDER BY SAL Desc) Emp_Rank
    FROM Emp)
    WHERE Emp_Rank <= 5;
  3. Using ROWNUM
    SELECT Empno, Ename, Job, Mgr, Hiredate, Sal
    FROM
    (SELECT Empno, Ename, Job, Mgr, Hiredate, Sal
    FROM Emp
    ORDER BY SAL Desc)
    WHERE ROWNUM <= 5;

Using ROWNUM to materialize an in-line view is not efficient, and it’s better to materialize the subquery using the SQL-99 WITH clause.  ROWNUM can cause performance problems.  Using ROWNUM may change the all_rows optimizer mode for a query to first_rows, causing unexpected sub-optimal execution plans.  One solution is to always include an all_rows hint when using ROWNUM to perform a top-n query.  See tuning SQL with “rownum”.

  • Share/Save/Bookmark

1 Response to "Oracle Top-N Query"

Hi,

Very good article. Thanks for providing such great tip.

Leave a Reply


Edi Yanto
Oracle Applications Technical Consultant
View Edi Yanto's profile on LinkedIn
Edi Yanto (何 萬 新) - Blogged Google PageRank Checker

My Certifications

Sponsored Links


  • Edi Yanto: have you download the fndconc.pll at the above link (http://www.ediyanto.co.cc/wp-content/uploads/2009/07/fndconc.pll) ? Are u compile at the right
  • Rahul: Hi, Very good article. Thanks for providing such great tip.
  • Edi Yanto: Hi Herlambang, Untuk Internal Manager, sillahkan lakukan step dibawah ini: 1. login sebagai user oracle 2. masuk ke $APPLCSF/scripts/[SID]_[host

 

February 2010
M T W T F S S
« Oct    
1234567
891011121314
15161718192021
22232425262728

Visitors

Categories

Blog Stats

Counter Powered by  RedCounter


Users Online