I am having a table looks like below.
I need second highest salary of all the employess table.
When I do below query I am getting expected result:
But it giving me empty result when i do
SELECT id,employee_id,name,salary
FROM `employess`
WHERE id not in (
select id from `employess`
where 1
group by employee_id
order by id desc)
GROUP BY employee_id
order by salary desc;
Second highest salaries of all the employess.
2
Answers
The subquery returns all employee IDs, so excluding them in the main query excludes everyone.
Change the subquery so it just returns the highest salary. Then exclude that salary, order by salary, and return the first of that.
Or return the ID of the employee with the highest salary and exclude them.
You can utilize the
dense_rank
function in MySQL to sort employees based on their highest salaries. Then, you filter the results using thewhere
clause to obtain the second-highest salary from employees, as you desire.For further information about
dense_rank
, you can visit the official MySQL documentation.