What is the highest salary in each department using SQL?
In many tech interviews, especially for positions involving database management and analysis, a common question revolves around how to extract specific data from a database. One frequently asked question is about how to find the highest salary in each department using SQL. Understanding this concept is critical for demonstrating proficiency in SQL and database querying.
To solve the problem, let’s assume we have a table named employees
with the following structure:
employee_id
: A unique identifier for each employee.name
: The name of the employee.department
: The department where the employee works.salary
: The salary of the employee.
Here is a sample structure of the employees
table:
employee_id | name | department | salary |
---|---|---|---|
1 | Alice | HR | 70000 |
2 | Bob | Engineering | 120000 |
3 | Carol | HR | 80000 |
4 | Dave | Engineering | 130000 |
5 | Eve | Marketing | 90000 |
6 | Frank | Marketing | 95000 |
To find the highest salary in each department, we can use the GROUP BY
clause combined with the MAX()
function in SQL. Here’s how to write the SQL query:
Sql
In this query, we are selecting two columns. The first is the department
, and the second is the highest salary in that department, which we calculate using the MAX(salary)
function. The GROUP BY department
clause categorizes the results by department, allowing us to calculate the maximum salary within each group.
When you run the above SQL query against our sample employees
table, you will receive the following result:
department | highest_salary |
---|---|
HR | 80000 |
Engineering | 130000 |
Marketing | 95000 |
This output correctly shows the highest salary for each department.
It is also common to need both the employee's name and their highest salary. To achieve this in SQL, we can use a subquery. The subquery will first find the highest salary per department, and then we will join this with the original table to get the corresponding employee names.
Here’s how you can achieve this:
Sql
In this query, we are joining the original employees
table e
with a derived table called max_salaries
that contains the highest salaries per department. This will yield the names of employees who earn the highest salary in their respective departments.
This approach illustrates not only how to fetch the highest salary but also demonstrates the importance of using joins and subqueries to expand on basic queries in SQL. Mastering these concepts is essential for anyone looking to succeed in tech interview scenarios related to SQL and data analysis.