SQL to find the nth highest value
Get the Nth largest value in a column using DENSE_RANK.
SELECT salary
FROM (
SELECT salary,
DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
FROM employees
) ranked
WHERE rnk = 3; -- the 3rd highest; change 3 to any NSELECT DISTINCT salary
FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 2; -- skip the top 2, take the nextOFFSET N-1 picks the Nth row. Use DENSE_RANK instead when equal values should share a rank.
How to find the nth highest value
To generalize 'second highest' to any position, rank the rows and pick the rank you want.
How it works
- DENSE_RANK() OVER (ORDER BY salary DESC) labels each distinct value with its position from the top.
- Filtering WHERE rnk = N returns the Nth highest distinct value.
- DISTINCT in the offset version collapses duplicate salaries so OFFSET counts distinct values, not rows.
Related SQL queries
- SQL to find the second highest value
- SQL to number and rank rows
- SQL to get the top n rows per group
- SQL to find duplicate rows
- SQL to delete duplicate rows (keep one)
- SQL to count rows per group
Frequently asked questions
How do I find the nth highest value in SQL?
To generalize 'second highest' to any position, rank the rows and pick the rank you want. DENSE_RANK() OVER (ORDER BY salary DESC) labels each distinct value with its position from the top. Filtering WHERE rnk = N returns the Nth highest distinct value. DISTINCT in the offset version collapses duplicate salaries so OFFSET counts distinct values, not rows.
Does this work in PostgreSQL, MySQL, SQL Server, and SQLite?
Yes — this page lists the query for each dialect, since the syntax can differ between database engines.
Can I generate this query for my own tables?
Yes. Describe what you want in plain English with Forgly's free AI SQL Generator and it writes the query for your dialect.