Monday, July 30, 2012

How to find second highest salary in MySQL


if you have MySQL table like below image


if you want to fetch second highest salary of employee following query will be useful for you.
select sal from emp group by sal order by sal desc Limit 1,1

your output will be like below image


if you want to fetch all employee which have second highest salary following query will be useful for you.
select * from emp where sal=(select sal from emp group by sal order by sal desc Limit 1,1)

your output will be like below image


One more query
SELECT * FROM  `users` WHERE  `id` = ( SELECT MAX( id ) -1 FROM  `users` )

SELECT * FROM  `users` WHERE  `id` < ( SELECT MAX( id ) -1 FROM  `users` ) ORDER BY id DESC LIMIT 1


1 comment:

  1. It help me lot this question is asked in interview thanks
    Nice post

    ReplyDelete