Tuesday, January 14, 2014

22. Write a SQL to find the third highest salary ?



In Oracle:


select * from
         (select * from
                         (select emp_name, sal from employee order by sal desc)
          where rownum < 4 order by sal)
where rownum = 1;


In SQL Server using TOP keyword:

SELECT TOP 1 Salary FROM
           ( SELECT DISTINCT TOP N Salary 
             FROM Employee 
             ORDER BY Salary DESC ) 
AS Emp ORDER BY Salary;


1 comment:

  1. I think this is not the way answer will come. suppose there are 3 salaries which are equal. Then it will not retrieve the right answer.

    To get the 3rd maximum salary below query can be used.
    select distinct sal from emp a where 3=(select count(distinct sal) from emp b where a.sal<b.sal) order by sal desc;

    ReplyDelete