Social Icons

Thursday, June 6, 2013

Find 2nd highest or nth highest salary of employee in sql

It is one of the common questions for developers and also asked in interviews frequently to find 2nd highest salary or nth highest salary of an employee from the employee table. Here, I am providing solution for both.

To find 2nd highest (or maximum) salary of employee, you can write your query like this in MySql:

Select max(salary) as salary 
From employees 
Where salary<(Select max(salary) From employees);

The above sql query will give you the 2nd highest salary of employee. Here, 'employees' is the name of the table in the database.

But, what if you have to find 3rd highest or 4th highest or nth highest salary of employee. If you will follow the above approach then you will have to write the subquery for n times. That doesn't seem good. Here, I am providing a generalized solution to find nth highest salary.  Look at the below sql query:


SELECT DISTINCT(salary) 
FROM employees 
ORDER BY salary DESC LIMIT (n-1) , 1


Here, n is the highest term for which you have to find out highest salary. The above query will give you nth highest salary.

No comments:

Post a Comment

Total Pageviews