Table: Employee
+--------------+---------+
| Column Name | Type |
+--------------+---------+
| id | int |
| name | varchar |
| salary | int |
| departmentId | int |
+--------------+---------+
id is the primary key (column with unique values) for this table.
departmentId is a foreign key (reference columns) of the ID from the Department table.
Each row of this table indicates the ID, name, and salary of an employee. It also contains the ID of their department.
Table: Department
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| id | int |
| name | varchar |
+-------------+---------+
id is the primary key (column with unique values) for this table. It is guaranteed that department name is not NULL.
Each row of this table indicates the ID of a department and its name.
Write a solution to find employees who have the highest salary in each of the departments.
Return the result table in any order.
The result format is in the following example.
Example 1:
Input: 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: +------------+----------+--------+ | Department | Employee | Salary | +------------+----------+--------+ | IT | Jim | 90000 | | Sales | Henry | 80000 | | IT | Max | 90000 | +------------+----------+--------+ Explanation: Max and Jim both have the highest salary in the IT department and Henry has the highest salary in the Sales department.
Problem Overview: The query must return the employee(s) who earn the highest salary in each department. The output includes the department name, employee name, and their salary. Multiple employees may appear for a department if they share the same maximum salary.
Approach 1: SQL Group By and Join (Time: O(n log n), Space: O(n))
This approach computes the maximum salary per department using GROUP BY. A subquery first scans the Employee table and calculates MAX(salary) for each departmentId. The result is then joined back with the original Employee table to retrieve the employee rows that match those maximum salaries. Finally, another join connects the result with the Department table to get department names. This pattern is common in SQL queries where aggregated results must be mapped back to detailed records.
Approach 2: Nested Queries with Join (Time: O(n log n), Space: O(n))
The nested query approach embeds the maximum salary calculation directly inside the filtering condition. For each employee, a correlated subquery checks whether their salary equals the maximum salary for that department. The database engine evaluates the inner query grouped by department and filters matching rows. While logically straightforward, correlated subqueries may be slightly less efficient depending on query planning. This method is still widely used in database interview questions because the logic closely mirrors the problem statement.
Approach 3: SQL Subquery Approach (Time: O(n log n), Space: O(n))
Another clean pattern uses a derived table containing departmentId and MAX(salary). The outer query joins this derived table with Employee and Department. The key insight is separating aggregation and filtering into two logical steps: first compute department-level metrics, then match employees who satisfy that metric. Query optimizers usually handle this efficiently using indexes and hash joins.
Approach 4: SQL Window Functions Approach (Time: O(n log n), Space: O(n))
Window functions compute rankings inside partitions. Using RANK() or DENSE_RANK() with PARTITION BY departmentId ORDER BY salary DESC assigns rank 1 to the highest-paid employees within each department. Filtering rows where rank equals 1 directly produces the answer. This approach avoids explicit aggregation joins and keeps the logic compact. Window functions are a powerful feature in modern SQL window functions workflows.
Recommended for interviews: The GROUP BY + JOIN approach is the safest answer because it demonstrates understanding of aggregation and relational joins. Window functions are often considered the cleanest modern solution and show stronger SQL fluency. Knowing both patterns signals strong database query skills.
This approach involves using SQL queries to retrieve the required data. We'll utilize the GROUP BY clause to segregate data by department, and the MAX function to determine the highest salary within each department. By joining the Employee table and the Department table, we can extract both the department name and the pertinent employee information.
Here, we first perform a JOIN operation between the Employee and Department tables based on departmentId. The subquery inside filters out the department-wise maximum salary using GROUP BY and MAX functions. The result is a list of employees with the highest salaries in each department, which is then retrieved using the outer query.
Time Complexity: O(N) where N is the number of employees, assuming indexing on join fields.
Space Complexity: O(N) for storing the intermediate join results and final results.
This method leverages nested SQL queries to first compute the maximum salary in each department and then joins these results back to the Employee table. The primary objective is to match employees with these max salaries and retrieve both their names and department names.
We utilize a Common Table Expression (CTE) to store maximum salaries per department (MaxSalaries) and join this temporary result back with the Employee table to filter out those employees who have these maximum salaries. Another join fetches department names from the Department table. This ensures that the results list the highest-paid employees by department.
Time Complexity: O(N log N) due to subquery operations and sorting for determining max.
Space Complexity: O(N) for storing intermediate JOIN and final results.
This approach involves using an SQL subquery in conjunction with the JOIN operation. We first determine the maximum salary for each department by grouping the Employee table by departmentId. Then, we use this result to join back to the Employee table and select the employee records that match these maximum salaries.
This query works in two main steps:
Time Complexity: O(N * M), where N is the number of employees and M is the number of departments. The subquery is executed for each employee record, comparing salaries within the department.
Space Complexity: O(N), for storing the result set.
This approach utilizes SQL window functions to eliminate the need for subqueries. By using the RANK() function over each department's salary list, you can directly identify which employees have the maximum salary in their respective departments.
The query involves the following major elements:
Time Complexity: O(N log N), where N is the number of employees. The RANK function operates in a similar way to a sort operation within each partition of the dataset.
Space Complexity: O(N), for storing ranking results and generating output.
| Approach | Complexity |
|---|---|
| SQL Group By and Join | Time Complexity: O(N) where N is the number of employees, assuming indexing on join fields. |
| Nested Queries with Join | Time Complexity: O(N log N) due to subquery operations and sorting for determining max. |
| SQL Subquery Approach | Time Complexity: O(N * M), where N is the number of employees and M is the number of departments. The subquery is executed for each employee record, comparing salaries within the department. |
| SQL Window Functions Approach | Time Complexity: O(N log N), where N is the number of employees. The RANK function operates in a similar way to a sort operation within each partition of the dataset. |
| Approach | Time | Space | When to Use |
|---|---|---|---|
| GROUP BY + Join | O(n log n) | O(n) | Most common SQL interview pattern for combining aggregates with row data |
| Nested Query with Join | O(n log n) | O(n) | Readable solution when matching rows against a department-level maximum |
| Derived Table Subquery | O(n log n) | O(n) | Useful when separating aggregation logic from filtering logic |
| Window Functions (RANK / DENSE_RANK) | O(n log n) | O(n) | Cleanest modern SQL solution when window functions are supported |
LeetCode 185: Department Top Three Salaries [SQL] • Frederik Müller • 15,937 views views
Watch 9 more video solutions →Practice Department Highest Salary with our built-in code editor and test cases.
Practice on FleetCode