SQL Query To Find Second Highest Salary - GeeksforGeeks
SQL Query To Find Second Highest Salary - GeeksforGeeks
Highest Salary
There are a lot of real-world scenarios where a query for finding the
nth salary will be really useful. Considering finding the second-
highest salary in SQL, we have one sample table.
Name Salary
Aman 100000
Shubham 1000000
Naveen 40000
Nishant 500000
How to find the employee whose salary is the second highest. For
example, in the above table, “Nishant ” has the second highest salary
at 500000.
Output:
Name Salary
Nishant 500000
WITH T ASd
(
SELECT *
DENSE_RANK() OVER (ORDER BY Salary Desc) AS Rnk
FROM Employees
)
SELECT Name
FROM T
WHERE Rnk=2;
How to find the third-largest salary?
Note that instead of nesting for the second, third, etc largest salary,
we can find the nth salary using a general query like in MySQL:
SELECT salary
FROM employee
ORDER BY salary desc limit n-1,1
We can clearly understand from the error message that our query is
an aggregation query from ‘MAX(salary)’ and at the same time, it
uses an unaggregated column ‘name’, which creates ambiguity for
MySQL. This error will be captured by those versions of MySQL
which contain the value ‘only_full_group_by’ in the ‘sql_mode’
variable. We can check this variable in MySQL using the following
command.