As asked
Given a table employee(department_id INT, employee_name VARCHAR, salary DECIMAL), write a SQL query to return the second-highest salary in each department. Handle ties correctly: if two employees share the highest salary, neither qualifies as second-highest.
Sample answer outline
Use DENSE_RANK() OVER (PARTITION BY department_id ORDER BY salary DESC) to assign ranks, then filter WHERE rnk = 2. Distinguish RANK (skips numbers after ties), DENSE_RANK (no gaps), and ROW_NUMBER (assigns arbitrary tiebreaker). The question tests understanding that ROW_NUMBER would give wrong results on ties here.
Reference implementation (sql)
SELECT department_id, employee_name, salary
FROM (
SELECT
department_id,
employee_name,
salary,
DENSE_RANK() OVER (
PARTITION BY department_id
ORDER BY salary DESC
) AS rnk
FROM employee
) ranked
WHERE rnk = 2;Expect these follow-ups
- What if you wanted the top 3 salaries per department, including ties at position 3?
- How does this query change if you need to return NULL when a department has fewer than 2 distinct salary levels?