SQL
Retrieve the Nth Highest Value Using DENSE_RANK()
Discover how to find the Nth highest value within a dataset using SQL's DENSE_RANK() window function, providing an efficient way to rank and select specific records.
WITH RankedSalaries AS (
SELECT
employee_id,
salary,
DENSE_RANK() OVER (ORDER BY salary DESC) as rank_num
FROM employees
)
SELECT
employee_id,
salary
FROM RankedSalaries
WHERE rank_num = 3; -- For the 3rd highest salary
How it works: This snippet uses a Common Table Expression (CTE) and the `DENSE_RANK()` window function to find the Nth highest salary. `DENSE_RANK()` assigns a rank to each row within a partition (here, the entire table ordered by salary descending), giving the same rank to rows with identical values. By querying the CTE for `rank_num = 3`, you retrieve all employees with the 3rd highest salary.