๐๐ป๐๐ฒ๐ฟ๐๐ถ๐ฒ๐๐ฒ๐ฟ:
You have 2 minutes to solve this SQL query.
Find the third highest salary from the employees table without using LIMIT or TOP.
๐ ๐ฒ: Challenge accepted! ๐ช
SELECT
salary
FROM (
SELECT
salary,
DENSE_RANK() OVER (ORDER BY salary DESC) AS salary_rank
FROM employees
) ranked
WHERE salary_rank = 3;
๐ก Explanation:
This query uses the DENSE_RANK() window function to rank distinct salary values in descending order.
โข ORDER BY salary DESC assigns Rank 1 to the highest salary.
โข DENSE_RANK() ensures duplicate salaries receive the same rank.
โข The outer query filters for salary_rank = 3, returning the third highest distinct salary.
๐ฏ Expected Output Example
Salary Rank
95,000 1
90,000 2
85,000 3
Output:
Third Highest Salary
85,000
๐ Alternative Solution Using a Correlated Subquery
SELECT DISTINCT salary
FROM employees e1
WHERE 2 = (
SELECT COUNT(DISTINCT salary)
FROM employees e2
WHERE e2.salary > e1.salary
);
This solution avoids window functions and is commonly asked to test your understanding of correlated subqueries.
๐ Questions involving the Nth highest or Nth lowest value are interview favorites. Be comfortable solving them using:
1. DENSE_RANK()
2. RANK()
3. Correlated Subqueries
4. Common Table Expressions (CTEs)
Being able to provide multiple approaches leaves a strong impression on interviewers.
โค๏ธ React with โค๏ธ for more interview challenges!
Post #2904
4.94K
- โค 17