Problem Description –
Employee table holds all employees including their managers. Every employee has an Id, and there is also a column for the manager Id.
Employee table, write a SQL query that finds out employees who earn more than their managers. For the above table, Joe is the only employee who earns more than his manager.
Difficulty Level – Easy
SELECT emp.Name as Employee FROM employee AS emp JOIN employee AS man ON emp.ManagerId = man.Id WHERE emp.Salary > man.Salary
To solve this problem, we need to join the Employee table to itself using a self-join. If we run the following query
SELECT * FROM employee AS emp JOIN employee AS man ON emp.ManagerId = man.Id
The output will be –
Here, the left table belongs to the employee and the right table belongs to the managers. And to join the manager table, you need to find a common key in the left table that maches with the manager table that is why we used
ON emp.ManagerId = man.Id . Now, if we look at both the row, we can see that Joe is the only employee whose salary ( 70000 ) is greater than his manager’s salary (60000 ). So, to select this employee, we used the
emp.Salary > man.Salary in the WHERE clause.