Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the employee with the second highest salary?

Tags:

sql

oracle

top-n

Is there any predefined function or method available to get the second highest salary from an employee table?

like image 638
Anil Avatar asked Jan 23 '23 09:01

Anil


1 Answers

The way to do this is with Oracle's Analytic functions. Your particular scenario is just a variant on the solution I provided in another thread.

If you are interested in just selecting the second highest salary then any of DENSE_RANK(), RANK() and ROW_NUMBER() will do the trick:

SQL> select * from
  2   ( select sal
  3            , rank() over (order by sal desc) as rnk
  4     from
  5      ( select distinct sal
  6        from emp )
  7    )
  8  where rnk = 2
  9  /

       SAL        RNK
---------- ----------
      3000          2

SQL> 

However, if you want to select additional information, such as the name of the employee with the second highest salary, the function you choose will affect the result. The main reason for choosing one over another is what happens when there is a tie.

If you use ROW_NUMBER() it will return the second employee ordered by salary: what if there are two employees tying for the highest salary? What if there are two employees tying for the second highest salary? Wheareas if you use RANK() and there are two employees tying for first highest salary, there will be no records with RANK = 2.

I suggest DENSE_RANK() is the usually the safest function to choose in these cases, but it really does depend on the specific business requirement.

like image 109
APC Avatar answered Feb 01 '23 13:02

APC