PostgreSQL Query to Find Employees with Salaries Higher Than Their Departmental Average
Last Updated :
24 Apr, 2024
In fact, in any organization, pay gaps exist among staff who are placed in different job categories based on their level of experience, skills, and negotiating power. On the other hand, when more employees make more than their department’s average, it tempts one to ask about fairness and equity.
In this article, we will discover how to use PostgreSQL to identify those employees gaining salaries higher than their departmental averages and examine some of the management implications and actions.
Understanding the Data
Let's begin by looking into the dataset structure. We'll assume a relational database schema with tables for employees and departments. Every employee record consists of fields: employee ID, name, department ID, and salary. Similarly, the department's table holds information about department IDs and names.
We'll need to perform a series of SQL queries to identify employees with salaries higher than their departmental averages. We will do these in four steps:
- Create tables and insert data into them.
- Calculate the departmental average salaries.
- Join the result with the employee's table.
- Find out employees whose salaries are higher than their departmental averages.
Step 1 - Create tables named departments and employees and insert data into them.
Query:
CREATE TABLE departments (
department_id SERIAL PRIMARY KEY,
department_name VARCHAR(100)
);
CREATE TABLE employees (
employee_id SERIAL PRIMARY KEY,
name VARCHAR(100),
department_id INT,
salary NUMERIC(10, 2),
FOREIGN KEY (department_id) REFERENCES departments(department_id)
);
INSERT INTO departments (department_name) VALUES
('HR'),
('Finance'),
('Marketing');
INSERT INTO employees (name, department_id, salary) VALUES
('Minal Pandey', 1, 60000.00),
('Vardhana Sharma', 1, 65000.00),
('Kavya Sharma', 2, 70000.00),
('Soni Pandey', 2, 75000.00),
('Mahi Pandey', 3, 62000.00),
('Abhilekh Pandey', 3, 68000.00),
('Vivek Sharma', 3, 71000.00);
Output:
You can see the content of both the table below:
Employees Table:
Employees TableDepartments Table:
Department TableStep 2 - Calculate the departmental average salaries.
Query:
SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id;
Output:
Department average salariesExplanation: The output presents the department IDs along with their average salaries computed from employee data. HR's average salary is 62,500, Finance's is 72,500, and Marketing's is 67,000. This information provides insight into salary distributions across different departments within the organization.
Step 3 - Join the above result with the employees table to associate each employee with their departmental average.
Query:
SELECT e.employee_id, e.name, e.salary, d.department_id, d.avg_salary
FROM employees e
JOIN (SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id) d
ON e.department_id = d.department_id;
Output:
Result after Joining tablesExplanation: The output presents employee details alongside their respective department IDs and salaries. Additionally, it includes the average salary for each department. This provides a comparison between individual employee salaries and the average salary within their respective departments, aiding in identifying discrepancies or outliers in salary distributions.
Step 4 - Filter out employees whose salaries exceed their departmental averages.
Query:
SELECT *
FROM (
SELECT e.employee_id, e.name, e.salary, d.department_id, d.avg_salary
FROM employees e
JOIN (SELECT department_id, AVG(salary) AS avg_salary
FROM employees
GROUP BY department_id) d
ON e.department_id = d.department_id
) AS subquery
WHERE salary > avg_salary;
Output:
EmployeesExplanation: The output shows employees earning more than the average salary in their department. It includes their ID, name, salary, department ID, and the department's average salary. This comparison reveals employees earning higher-than-average wages within their departments, giving a snapshot of salary discrepancies.
Conclusion
Through the implementation of these SQL queries in PostgreSQL, it will be more feasible to recognize employees getting more than their departmental averages. This analysis provide managerial executives valuable insights to review and assess salary structures, deal with variations, and promote fairness and transparency. Furthermore, these parameters can be utilized in the process of developing a culture of equity and workforce satisfaction which is also very important.
Similar Reads
SQL Interview Questions
Are you preparing for a SQL interview? SQL is a standard database language used for accessing and manipulating data in databases. It stands for Structured Query Language and was developed by IBM in the 1970s, SQL allows us to create, read, update, and delete data with simple yet effective commands.
15+ min read
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
SQL Tutorial
SQL is a Structured query language used to access and manipulate data in databases. SQL stands for Structured Query Language. We can create, update, delete, and retrieve data in databases like MySQL, Oracle, PostgreSQL, etc. Overall, SQL is a query language that communicates with databases.In this S
11 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands
SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
SQL Joins (Inner, Left, Right and Full Join)
SQL joins are fundamental tools for combining data from multiple tables in relational databases. Joins allow efficient data retrieval, which is essential for generating meaningful observations and solving complex business queries. Understanding SQL join types, such as INNER JOIN, LEFT JOIN, RIGHT JO
6 min read
Normal Forms in DBMS
In the world of database management, Normal Forms are important for ensuring that data is structured logically, reducing redundancy, and maintaining data integrity. When working with databases, especially relational databases, it is critical to follow normalization techniques that help to eliminate
8 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
ACID Properties in DBMS
In the world of Database Management Systems (DBMS), transactions are fundamental operations that allow us to modify and retrieve data. However, to ensure the integrity of a database, it is important that these transactions are executed in a way that maintains consistency, correctness, and reliabilit
8 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Backpropagation in Neural Network
Backpropagation is also known as "Backward Propagation of Errors" and it is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network. In this article we will explore what
10 min read