Mysql query to get 2nd highest salary

Consider the employee table with the fields emp_id and salary.

emp_id salary
1 10000
2 30000
3 15000
4 50000
5 25000

Now if you want get the 1st highest salary then you can use the below query

SELECT DISTINCT `salary` FROM `employee`ORDER BY `salary` DESC LIMIT 0, 1

RESULT: 50000

To find the 2nd highest salary then you can use the following query

SELECT DISTINCT `salary` FROM `employee`ORDER BY `salary` DESC LIMIT 1, 1

RESULT: 30000

Likewise you can find the any of the highest salary using the above query by changing the LIMIT value

Also you can find the highest salary in many other ways but this one of the easy way to find the highest salary.

Note: This is the most common question asked in many of the interviews

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s