Open In App

SQL Query to Find the Highest Salary of Each Department

Last Updated : 03 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Structured Query Language (SQL) is a standard database language widely used for managing, maintaining, and retrieving data from relational databases like MySQL, Oracle, and Microsoft SQL Server. In this article, we will demonstrate how to use SQL to find the highest salary in each department. This is an essential query in scenarios such as analyzing departmental budgets or rewarding top-performing employees.

Finding the Highest Salary in Each Department Using SQL

Step 1: Create the Database

We start by creating a database named geeks:

CREATE geeks;

To use this database:

USE geeks;

Step 2: Create the Table

This is our table in the geeks database:

CREATE TABLE department(
ID int,
SALARY int,
NAME Varchar(20),
DEPT_ID Varchar(255));

Step 3: View the Table Structure

To verify the structure of the department table:

EXEC sp_columns department;

Output

Step 4: Insert Sample Data

INSERT INTO department VALUES (1, 34000, 'ANURAG', 'UI DEVELOPERS');
INSERT INTO department VALUES (2, 33000, 'harsh', 'BACKEND DEVELOPERS');
INSERT INTO department VALUES (3, 36000, 'SUMIT', 'BACKEND DEVELOPERS');
INSERT INTO department VALUES (4, 36000, 'RUHI', 'UI DEVELOPERS');
INSERT INTO department VALUES (5, 37000, 'KAE', 'UI DEVELOPERS');

To confirm the data, retrieve all rows:

SELECT * FROM department;

Step 5: Write the Query to Find the Highest Salary

To find the highest salary in each department, we use the MAX() aggregate function combined with GROUP BY. Here our table contains a DEPT_ID and it has two different categories UI DEVELOPERS and BACKEND DEVELOPERS.

Syntax

SELECT colunm_name, MAX(column_name) FROM table_name GROUP BY column_name;

Example

SELECT DEPT_ID, MAX(SALARY) AS HIGHEST_SALARY
FROM department
GROUP BY DEPT_ID;

Output

Explanation:

  • The highest salary in the UI DEVELOPERS department is 37000, held by KAE.
  • The highest salary in the BACKEND DEVELOPERS department is 36000, held by SUMIT.

Conclusion

Using SQL's GROUP BY and MAX() aggregate function, we can efficiently calculate the highest salary for each department in our database. This is a commonly used query in HR management systems, finance, and other applications. By following this article, we can extend the logic to analyze other metrics, such as minimum salary, average salary, and more.


Next Article
Article Tags :

Similar Reads