Employees Earning More Than Their Managers SQL Challenge - PostgreSQL Solution

1. Introduction

In this blog post, we will explore how to find employees who earn more than their managers using PostgreSQL. This is an interesting problem that can help us understand more about self-joins and conditional data retrieval in SQL.

Problem

The challenge is to create a PostgreSQL query that identifies employees whose salaries are higher than their managers' salaries in a given table.

Database Table:

Employee Table:
Id Name Salary ManagerId
1 Alice 7000 4
2 Bob 6000 4
3 Charlie 5000 4

3. PostgreSQL Solution

SELECT e1.Name AS Employee
FROM Employee e1
JOIN Employee e2 ON e1.ManagerId = e2.Id
WHERE e1.Salary > e2.Salary;

Output:

Employee
Alice
Bob

Explanation:

1. The solution involves a self-join on the Employee table.

2. Each employee (e1) is joined with their manager (e2) using the ManagerId.

3. The WHERE clause is used to compare the salaries of the employee and the manager.

4. The query outputs the names of employees who have a higher salary than their managers.


Comments