Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (20.3k points)

What's the difference between RANK() and DENSE_RANK() functions? How to find out nth salary in the following emptbl table?

DEPTNO  EMPNAME    SAL

------------------------------

10       rrr    10000.00

11       nnn    20000.00

11       mmm    5000.00

12       kkk    30000.00

10       fff    40000.00

10       ddd    40000.00

10       bbb    50000.00

10       ccc    50000.00

If in the table data having nulls, what will happen if I want to find out the nth salary?

1 Answer

0 votes
by (40.7k points)

RANK: This gives you the ranking within your ordered partition. Ties are assigned the same rank, with the next ranking(s) skipped. Therefore, if you have 3 items at rank 2, the next rank listed will be ranked 5.

DENSE_RANK: This gives you the ranking within your ordered partition, but the ranks are consecutive in it. Also, no ranks are skipped if there are ranks with multiple items.

Note: For nulls, ranking depends on the ORDER BY clause. 

Following is the test script you can use to see what happens:

Query:

with q as (

select 10 deptno, 'rrr' empname, 10000.00 sal from dual union all

select 11, 'nnn', 20000.00 from dual union all

select 11, 'mmm', 5000.00 from dual union all

select 12, 'kkk', 30000 from dual union all

select 10, 'fff', 40000 from dual union all

select 10, 'ddd', 40000 from dual union all

select 10, 'bbb', 50000 from dual union all

select 10, 'xxx', null from dual union all

select 10, 'ccc', 50000 from dual)

select empname, deptno, sal

     , rank() over (partition by deptno order by sal nulls first) r

     , dense_rank() over (partition by deptno order by sal nulls first) dr1

     , dense_rank() over (partition by deptno order by sal nulls last) dr2

 from q; 

EMP     DEPTNO        SAL          R        DR1        DR2

--- ---------- ---------- ---------- ---------- ----------

xxx         10                     1          1          4

rrr         10      10000          2          2          1

fff         10      40000          3          3          2

ddd         10      40000          3          3          2

ccc         10      50000          5          4          3

bbb         10      50000          5          4          3

mmm         11       5000          1          1          1

nnn         11      20000          2          2          2

kkk         12      30000          1          1          1

9 rows got selected.

For more information, refer to this link:

https://oracle-base.com/articles/misc/rank-dense-rank-first-last-analytic-functions

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 31, 2019 in SQL by Tech4ever (20.3k points)

Browse Categories

...