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

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


  • Yulisar Ganda Putra: Terima Kasih banyak Pak Edi Yanto, arahan bapak sangat membantu, kendala yang saya hadapi sekarang sudah solve
  • Miki: Edi, Same thing happened when I changed the data type in table! Is there any chance to 'resize' (convert) existing blob images? Thanks, Mi
  • Edi Yanto: Hi Miki, How about the result if you change the data type of the image column to BLOB data type? Thanks, Edi

 

November 2009
M T W T F S S
« Oct    
 1
2345678
9101112131415
16171819202122
23242526272829
30  

Visitors

Categories

Blog Stats

Counter Powered by  RedCounter


Users Online