I recenly learned that it's possible to to join a SQL table with itself.
Consider the following table. We would like to find the name of the employees who make more money than their manager.
Table: Employees
| id | name | salary | manager_id |
|---|---|---|---|
| 1 | Khaled | 5000 | 3 |
| 2 | Takayuki | 3500 | 3 |
| 3 | Elena | 4000 | null |
| 4 | Alvin | 4000 | null |
The below query would join Employees with itself.
SELECT * FROM Employees e
JOIN Employees m ON e.manager_id = m.id;
This would be the output.
| id | name | salary | manager_id | id | name | salary | manager_id |
|---|---|---|---|---|---|---|---|
| 1 | Khaled | 5000 | 3 | 3 | Elena | 4000 | null |
| 2 | Takayuki | 3500 | 3 | 3 | Elena | 4000 | null |
By editing the SELECT statement, and adding a WHEREstatement, we accomplish our goal.
SELECT e.name FROM Employees e
JOIN Employees m ON e.manager_id = m.id
WHERE e.salary > m.salary;
Voila!
| name |
|---|
| Khaled |