SQL
Find Nth Highest Value in SQL
Discover how to retrieve the Nth highest value from a column in SQL using DENSE_RANK() or a subquery, a fundamental skill for data analysis.
WITH RankedSalaries AS (
SELECT
employee_id,
salary,
DENSE_RANK() OVER (ORDER BY salary DESC) as rank_num
FROM
Employees
)
SELECT
salary
FROM
RankedSalaries
WHERE
rank_num = 2; -- For the 2nd highest salary
How it works: This query finds the Nth highest salary (e.g., 2nd highest in this example). It uses a Common Table Expression (CTE) named `RankedSalaries` to assign a dense rank to each salary in descending order. `DENSE_RANK()` assigns the same rank to employees with identical salaries, ensuring no gaps in the ranking. Finally, it selects salaries where the `rank_num` matches the desired N.