181. Employees Earning More Than Their Managers


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      |
+----------+

b'
\n\n

Solution

\n
\n

Approach I: Using WHERE clause [Accepted]

\n

Algorithm

\n

As this table has the employee\'s manager information, we probably need to select information from it twice.

\n
SELECT *\nFROM Employee AS a, Employee AS b\n;\n
\n
\n

Note: The keyword \'AS\' is optional.

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
IdNameSalaryManagerIdIdNameSalaryManagerId
1Joe7000031Joe700003
2Henry8000041Joe700003
3Sam600001Joe700003
4Max900001Joe700003
1Joe7000032Henry800004
2Henry8000042Henry800004
3Sam600002Henry800004
4Max900002Henry800004
1Joe7000033Sam60000
2Henry8000043Sam60000
3Sam600003Sam60000
4Max900003Sam60000
1Joe7000034Max90000
2Henry8000044Max90000
3Sam600004Max90000
4Max900004Max90000
> The first 3 columns are from a and the last 3 ones are from b.
\n

Select from two tables will get the Cartesian product of these two tables. In this case, the output will be 4*4 = 16 records. However, what we interest is the employee\'s salary higher than his/her manager. So we should add two conditions in a WHERE clause like below.

\n
SELECT\n    *\nFROM\n    Employee AS a,\n    Employee AS b\nWHERE\n    a.ManagerId = b.Id\n        AND a.Salary > b.Salary\n;\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
IdNameSalaryManagerIdIdNameSalaryManagerId
1Joe7000033Sam60000
\n

As we only need to output the employee\'s name, so we modify the above code a little to get a solution.

\n

MySQL

\n
SELECT\n    a.Name AS \'Employee\'\nFROM\n    Employee AS a,\n    Employee AS b\nWHERE\n    a.ManagerId = b.Id\n        AND a.Salary > b.Salary\n;\n
\n

Approach I: Using JOIN clause [Accepted]

\n

Algorithm

\n

Actually, JOIN is a more common and efficient way to link tables together, and we can use ON to specify some conditions.

\n
SELECT\n     a.NAME AS Employee\nFROM Employee AS a JOIN Employee AS b\n     ON a.ManagerId = b.Id\n     AND a.Salary > b.Salary\n;\n
\n
'