Department Highest Salary
Write an SQL query to find employees who have the highest salary in each of the departments. Return the result table in **any order**. ### Table: Employee | Column Name | Type | | :--- | :--- | | id | int | | name | varchar | | salary | int | | departmentId | int | `id` is the primary key column for this table. `departmentId` is a foreign key of the ID from the Department table. ### Table: Department | Column Name | Type | | :--- | :--- | | id | int | | name | varchar | `id` is the primary key column for this table. ### Example: **Input:** ```text Employee table: +----+-------+--------+--------------+ | id | name | salary | departmentId | +----+-------+--------+--------------+ | 1 | Joe | 70000 | 1 | | 2 | Jim | 90000 | 1 | | 3 | Henry | 80000 | 2 | | 4 | Sam | 60000 | 2 | | 5 | Max | 90000 | 1 | +----+-------+--------+--------------+ Department table: +----+-------+ | id | name | +----+-------+ | 1 | IT | | 2 | Sales | +----+-------+ ``` **Output:** ```text +------------+----------+--------+ | Department | Employee | Salary | +------------+----------+--------+ | IT | Jim | 90000 | | IT | Max | 90000 | | Sales | Henry | 80000 | +------------+----------+--------+ ```
Solve It in the BrowserPractice Explaining It Out Loud
Optimal Approach
- Time complexity: O(N + M)
- Space complexity: O(N)
Scanning and grouping by department takes linear time O(N), followed by a hash join with Department (M).
Follow-Up Questions Interviewers Ask About Department Highest Salary
- How could you solve this problem using Window Functions in modern SQL?
You can use DENSE_RANK() OVER (PARTITION BY departmentId ORDER BY salary DESC) in a CTE or subquery, then select where rank = 1.
Practice the full problem with execution, tests, and AI code review in the interactive lab — then rehearse explaining your solution in a live voice mock interview.