How do you write a query to find the nth highest salary in the Employees table?
Posted by BobHarris
Last Updated: August 01, 2024
To find the nth highest salary in the Employees table, you can use various SQL techniques. One common method is to use a combination of DISTINCT, ORDER BY, and LIMIT (or OFFSET) depending on the database you are using. Here is a general SQL query structure that you can modify to fit your requirements:
For MySQL
SELECT DISTINCT salary
FROM Employees
ORDER BY salary DESC
LIMIT 1 OFFSET n-1;
Here, replace n with the desired rank (e.g., for the 3rd highest salary, use n=3).
For SQL Server
SELECT DISTINCT TOP 1 salary
FROM (
    SELECT DISTINCT salary
    FROM Employees
    ORDER BY salary DESC
) AS RankedSalaries
ORDER BY salary ASC;
You would need a common table expression or derived table to select the distinct salaries and then order them accordingly.
For PostgreSQL
SELECT DISTINCT salary
FROM Employees
ORDER BY salary DESC
OFFSET n-1 LIMIT 1;
For Oracle
In Oracle, you can use the ROW_NUMBER() function:
SELECT salary
FROM (
    SELECT salary, ROW_NUMBER() OVER (ORDER BY salary DESC) AS rank
    FROM (SELECT DISTINCT salary FROM Employees)
) 
WHERE rank = n;
Note
Make sure to handle cases where there are less than n distinct salaries in the table; these queries will return no results in such cases. Additionally, adjust the column and table names according to your database schema.