1. Introduction
This blog post addresses a common SQL query problem – identifying employees who earn more than their managers. We will demonstrate how to approach this using MySQL.
Problem
The challenge is to write a MySQL query for a database table where each employee's salary is compared to that of their manager. The query should find employees who earn more than their managers.
Database Table:
Employee Table:Id | Name | Salary | ManagerId |
---|---|---|---|
1 | John | 3000 | 3 |
2 | Mike | 4000 | 3 |
3 | Sally | 5000 | NULL |
3. MySQL Solution
SELECT e1.Name AS Employee
FROM Employee e1
JOIN Employee e2 ON e1.ManagerId = e2.Id
WHERE e1.Salary > e2.Salary;
Output:
Employee |
---|
John |
Mike |
Explanation:
1. The query performs a self-join on the Employee table.
2. It joins each employee (e1) with their manager (e2) using the ManagerId.
3. The WHERE clause filters out employees whose salary is greater than that of their manager.
4. The query lists the names of employees who earn more than their managers.
Comments
Post a Comment