How to Find the Nth Highest Salary in SQL: A Beginner’s Guide
If you’re just stepping into SQL or prepping for a job interview, you’ve probably come across this common question: How do you find the nth highest salary in a table? It may seem tricky at first, but with a clear understanding of SQL's ranking and filtering features, the solution becomes much more approachable.
In this beginner’s guide, we’ll explore various methods to retrieve the nth highest salary in SQL using simple examples and practical queries.
Why Is This Question So Popular?
This question helps interviewers assess your ability to:
-
Use SQL’s sorting and filtering features
-
Work with subqueries or window functions
-
Understand and apply ranking logic
The “nth highest” concept can be applied to many real-world scenarios beyond salaries—like finding the nth top-selling product or nth most-viewed article—making it a valuable skill.
Scenario Setup
Let’s say you have a table called employees
like this:
id | name | salary |
---|---|---|
1 | Alice | 70000 |
2 | Bob | 85000 |
3 | Charlie | 60000 |
4 | Dave | 85000 |
5 | Eva | 90000 |
Now, let’s explore different ways to find the nth highest salary.
Method 1: Using LIMIT
with OFFSET
(MySQL, PostgreSQL)
A simple and intuitive approach if you're using MySQL or PostgreSQL.
Example: 3rd Highest Salary
This query sorts the salaries in descending order, skips the first two, and then returns the next one — the 3rd highest.
Good for: Simple scenarios with databases that support LIMIT
.
Method 2: Using DENSE_RANK()
(SQL Server, PostgreSQL, Oracle)
This method is more robust, especially when handling duplicate salaries.
Example: 2nd Highest Salary
This will return 85000 — even if it appears more than once, because DENSE_RANK
groups equal values with the same rank.
Good for: When you want to return all entries sharing the same salary rank.
Method 3: Using a Correlated Subquery (Generic SQL)
This method works across many SQL engines, even if they don't support advanced functions.
Example: 1st Highest Salary
This counts how many salaries are greater than each one, and selects the row where that count is exactly N-1
.
Good for: SQL engines without window functions.
Common Pitfalls to Avoid
-
Duplicate salaries: Be sure to use
DISTINCT
orDENSE_RANK()
to handle them correctly. -
NULL values: These can affect your sorting, so filter them out if needed.
-
Zero-based offset confusion: Remember,
OFFSET 0
gives the highest,OFFSET 1
gives the second highest, and so on.
Conclusion
Finding the nth highest salary in SQL is a foundational skill that teaches you how to think critically with queries. By understanding and applying methods like LIMIT & OFFSET
, DENSE_RANK()
, or correlated subqueries, you'll be well-equipped to tackle variations of this problem in any SQL environment.
Comments
Post a Comment