Pages

Wednesday, February 1, 2012

Third Highest Salary

Here is a database question asked usually during Interviews which I would like to share

Name Salary
A          50
B          20
C          30
D          40
E          30
F          40

Now out of these find employees with third highest salary

Here are steps to do so first let us sort in descending order and limit the same to third row

Select DISTINCT(Salary) from emp order by Salary DESC limit 2,1

Now this gives us 30 but we need salary of C and D as rows we take this as subquery

Select * from Emp where salary in( Select DISTINCT(Salary) from emp order by Salary DESC limit 2,1);
which is the correct answer