The Department Top Three Salaries interview question is an advanced version of the "Highest Salary" problem. You need to identify employees who earn one of the top three unique salaries in their department. If multiple employees earn the same salary, they all count toward that specific rank. This Department Top Three Salaries coding problem is a "Hard" SQL task because it involves multi-level filtering and ranking.
Tech giants like Apple and Meta use this question to test a candidate's mastery of complex SQL queries. It evaluates your understanding of how to handle "Top-N" queries within categories. It’s a classic Database interview pattern that checks if you can handle duplicate values (ties) correctly while limiting results.
This problem is best solved using the DENSE_RANK() Window Function.
DENSE_RANK() assigns ranks without gaps (e.g., 1, 1, 2, 3). This is crucial because the problem asks for the "top three unique salaries."OVER(PARTITION BY departmentId ORDER BY salary DESC).rank <= 3.IT Department Salaries: [90k, 90k, 85k, 80k, 70k].
RANK() would skip numbers (e.g., 1, 1, 3), potentially excluding the third highest salary if there's a tie at the top.Always clarify if "Top 3" refers to the top three people or the top three unique values. In database contexts, this distinction dictates whether you use ROW_NUMBER() or DENSE_RANK().