AdvancedAdvanced PostgreSQL
Find the Nth highest salary (multiple methods)
The query
SQL
-- Method 1: LIMIT OFFSET (simple but slow for large N)
SELECT DISTINCT salary
FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 2; -- 3rd highest (0-indexed)
-- Method 2: DENSE_RANK (recommended)
SELECT salary FROM (
SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
FROM employees
) t WHERE rnk = 3; -- Nth = 3
-- Method 3: Subquery
SELECT MIN(salary) FROM (
SELECT DISTINCT salary FROM employees
ORDER BY salary DESC LIMIT 3
) top3;Note
“DENSE_RANK method handles ties correctly. LIMIT OFFSET is simple but becomes slow for large N.