Welcome back to our JOINs course! In this part, we'll focus on joining tables with themselves!
Let's consider the following situation: we have information about employees and their supervisors in a single table, like this:
Employee |
Id |
Name |
SupervisorId |
Experience |
1 |
John |
0 |
15 |
2 |
Peter |
3 |
3 |
3 |
Casper |
1 |
2 |
4 |
Kate |
1 |
5 |
As you can see, there are four people. John is a supervisor to both Casper and Kate, and Casper is Peter's supervisor.
The Employee
table stores data in a hierarchical structure: employees and their supervisors. Storing a structure like this in a table is quite common. Imagine you want to list each employee's name along with the name of their supervisor. That's where JOINing a table with itself comes in handy:
SELECT
Emp.Name as EmployeeName,
Supervisor.Name as SupervisorName
FROM Employee as Emp
JOIN Employee as Supervisor
ON Emp.SupervisorId = Supervisor.Id
RESULT: |
EmployeeName |
SupervisorName |
Casper |
John |
Peter |
Casper |
Kate |
John |
When you join a table with itself, you must alias both occurrences of the table name. Moreover, the column names you refer to must be preceded by the alias of the table you want. This way, the database can distinguish which copy of the table you want to select a particular column from.