[leetcode/database] 181 employees earning more than their managers

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.

Problem

The Employee table holds all employees including their managers. Every employee has an Id, and there is also a column for the manager Id.

+----+-------+--------+-----------+
| Id | Name  | Salary | ManagerId |
+----+-------+--------+-----------+
| 1  | Joe   | 70000  | 3         |
| 2  | Henry | 80000  | 4         |
| 3  | Sam   | 60000  | NULL      |
| 4  | Max   | 90000  | NULL      |
+----+-------+--------+-----------+

Given the 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.

+----------+
| Employee |
+----------+
| Joe      |
+----------+

Solution

Using self join:

SELECT
a.NAME AS Employee
FROM Employee AS a JOIN Employee AS b
ON a.ManagerId = b.Id
AND a.Salary > b.Salary

SELF JOIN

The SQL SELF JOIN is used to join a table to itself as if the table were two tables.
The basic syntax of SELF JOIN is as follows:

SELECT a.column_name, b.column_name…
FROM table1 a, table1 b
WHERE a.common_field = b.common_field;

SELF JOIN returns the Cartesian product of rows from the rowsets in the join. In other words, it will combine each row from the first rowset with each row from the second rowset. Actually, it has the similar effect as using CROSS JOIN between two different tables.

Conclusion

As this table has the employee’s manager information, we need to select information from it twice. Though we can also solve the problem with WHERE & AND/OR, JOIN & ON is a more common and efficient way to link tables together.

Reference

1. Employees Earning More Than Their Managers Solution
2. SQL - SELF JOINS
3. Cartesian Product