Suppose that you are given the following simple database table called Employee that has 2 columns named Employee ID and Salary:
Employee
Employee ID S
I think, It is the simplest way to find MAX and second MAX Salary.You may try this way.
SELECT MAX(Salary) FROM Employee; -- For Maximum Salary.
SELECT MAX(Salary) FROM Employee WHERE Salary < (SELECT MAX(Salary) FROM Employee); -- For Second Maximum Salary
For unique salaries (i.e. first can't be same as second):
SELECT
MAX( s.salary ) AS max_salary,
(SELECT
MAX( salary )
FROM salaries
WHERE salary <> MAX( s.salary )
ORDER BY salary DESC
LIMIT 1
) AS 2nd_max_salary
FROM salaries s
And also because it's such an unnecessary way to go about solving this problem (Can anyone say 2 rows instead of 2 columns, LOL?)
You can write 2 subqueries like this example
SELECT (select max(Salary) from Employee) as max_id,
(select Salary from Employee order by Salary desc limit 1,1) as max_2nd
Here is another solution which uses sub query but instead of IN clause it uses < operator
SELECT MAX(Salary) From Employees WHERE Salary < ( SELECT Max(Salary) FROM Employees);
This is awesome Query to find the nth Maximum: For example: -
You want to find salary 8th row Salary, Just Changed the indexed value to 8.
Suppose you have 100 rows with Salary. Now you want to find Max salary for 90th row. Just changed the Indexed Value to 90.
set @n:=0;
select * from (select *, (@n:=@n+1) as indexed from employee order by Salary desc)t where t.indexed = 1;
For second highest salary, This one work for me:
SELECT salary
FROM employee
WHERE salary
NOT IN (
SELECT MAX( salary )
FROM employee
ORDER BY salary DESC
)
LIMIT 1