SQL ANSI: Find Nth Highest Salary with CTE
WITH RankedSalaries AS ( -- Assign a rank to each distinct salary in descending order SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) as salary_rank FROM ( -- Select only distinct salaries to avoid ranking duplicates multiple times SELECT DISTINCT salary FROM employees )...
This SQL query finds the Nth highest salary using Common Table Expressions (CTEs) and the DENSE_RANK() window function. It's designed to be flexible, allowing you to specify any rank 'N'. This is useful for salary analys...
The query first defines a CTE named 'RankedSalaries'. Inside the CTE, it selects distinct salaries from the 'employees' table. Then, it applies the DENSE_RANK() window function to these distinct salaries, ordering them in descending order. DENSE_RANK() assigns a rank to each unique salary, ensuring no gaps in ranking even if there are duplicate salaries. The main query then selects the salary from 'RankedSalaries' where the assigned rank matches the input parameter ':N'. This approach correctly handles duplicate salaries and ensures that if 'N' is larger than the number of distinct salaries, or if the table is empty, an empty result set is returned. The time complexity is typically O(N log N) or O(N) depending on the database's implementation of window functions and sorting, and space complexity is O(N) for storing distinct salaries and their ranks within the CTE.
1. Define a CTE 'RankedSalaries'. 2. Inside the CTE: a. Select distinct salaries from the employees table. b. Assign a dense rank to each distinct salary in descending order. 3. Select the salary from 'RankedSalaries' wh...