SQL
Finding the Nth Largest Value Using Subqueries
Discover how to retrieve the Nth largest value from a dataset using a correlated subquery, offering an alternative to window functions for specific use cases.
-- Find the 3rd largest salary
SELECT
salary
FROM
employees e1
WHERE
(SELECT COUNT(DISTINCT salary)
FROM employees e2
WHERE e2.salary >= e1.salary) = 3;
-- Generalizing for Nth largest (e.g., N=5)
SELECT
column_name
FROM
your_table t1
WHERE
(SELECT COUNT(DISTINCT column_name)
FROM your_table t2
WHERE t2.column_name >= t1.column_name) = N;
How it works: This snippet shows how to find the Nth largest value in a column without relying on window functions, which are explicitly forbidden for ranking in the prompt. It uses a correlated subquery that counts the number of distinct values greater than or equal to the current row's value. When this count equals N, we've found our Nth largest value. This is a classic approach useful for specific data retrieval challenges, especially in environments where advanced window functions might not be available or suitable.