Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The best way to do this is with analytic functions, RANK() or DENSE_RANK() ...</p> <pre><code>SQL&gt; select * from ( 2 select empno 3 , sal 4 , rank() over (order by sal desc) as rnk 5 from emp) 6 where rnk &lt;= 5 7 / EMPNO SAL RNK ---------- ---------- ---------- 7839 5000 1 7788 3000 2 7902 3000 2 7566 2975 4 8083 2850 5 7698 2850 5 6 rows selected. SQL&gt; </code></pre> <p>DENSE_RANK() compresses the gaps when there is a tie:</p> <pre><code>SQL&gt; select * from ( 2 select empno 3 , sal 4 , dense_rank() over (order by sal desc) as rnk 5 from emp) 6 where rnk &lt;= 5 7 / EMPNO SAL RNK ---------- ---------- ---------- 7839 5000 1 7788 3000 2 7902 3000 2 7566 2975 3 8083 2850 4 7698 2850 4 8070 2500 5 7 rows selected. SQL&gt; </code></pre> <p>Which behaviour you prefer depends upon your business requirements. </p> <p>There is also the ROW_NUMBER() analytic function which we can use to return a precise number of rows. However, we should avoid using solutions based on row number unless the business logic is happy to arbitrarily truncate the result set in the event of a tie. There is a difference between asking for <em>the five highest values</em> and the <em>first five records sorted by high values</em></p> <p>There is also a non-analytic solution using the ROWNUM pseudo-column. This is clunky because ROWNUM is applied before the ORDER BY clause, which can lead to unexpected results. There is rarely any reason to use ROWNUM instead of ROW_NUMBER() or one of the ranking functions.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload