Nth Highest Salary in SQL
How to Find the Nth Highest Salary in SQL
Finding the Nth highest salary means retrieving the salary that ranks Nth when salaries are sorted from highest to lowest.
Common Methods to Get Nth Highest Salary
1. Using ORDER BY with LIMIT / OFFSET (MySQL, PostgreSQL)
Example: Get the 3rd highest salary
SELECT DISTINCT salaryFROM employeesORDER BY salary DESCLIMIT 1 OFFSET 2;OFFSET 2skips the first two highest salaries, thenLIMIT 1fetches the next one (3rd highest).Use
DISTINCTto avoid duplicates messing the count.
2. Using Subquery with TOP (SQL Server)
SELECT DISTINCT TOP 1 salaryFROM employeesWHERE salary < ( SELECT DISTINCT TOP 2 salary FROM employees ORDER BY salary DESC)ORDER BY salary DESC;Explanation:
Inner query selects top 2 salaries,
Outer query selects the highest salary less than those (which is the 3rd highest).
3. Using ROW_NUMBER() or DENSE_RANK() Window Functions (Modern SQL)
Example for 3rd highest salary:
SELECT salaryFROM ( SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) as rank FROM employees) ranked_salariesWHERE rank = 3;DENSE_RANK()ranks salaries without skipping ranks for duplicates.You can use
ROW_NUMBER()if you want distinct rows ignoring duplicates.
4. Using Correlated Subquery (Works in many databases)
SELECT DISTINCT salaryFROM employees e1WHERE 3 = ( SELECT COUNT(DISTINCT salary) FROM employees e2 WHERE e2.salary >= e1.salary);Explanation:
For each salary, count how many salaries are greater or equal; when count = 3, it's the 3rd highest.
Summary:
| Method | Best For | Notes |
|---|---|---|
LIMIT with OFFSET | MySQL, PostgreSQL | Simple, but doesn't work in SQL Server |
TOP with subquery | SQL Server | Useful in older SQL Server versions |
Window functions (DENSE_RANK) | Most modern DBs | Clean, handles duplicates well |
| Correlated subquery | General compatibility | Less efficient for large datasets |
If you want, I can help write a query for your specific SQL database!