A self join joins a table to itself. It is an ordinary join, not a separate keyword; the only difference is that both sides are the same table, so each side needs its own alias to tell them apart.
SELECT a.column, b.columnFROM table_name AS aINNER JOIN table_name AS b ON a.column = b.other_column;It is useful whenever rows of a table point at other rows of the same table. The examples use the Crew table from the example database, where ReportsTo holds the CrewID of each person’s manager.
Each person and their manager
Section titled “Each person and their manager”Read Crew twice: once as the staff, once as the managers. Join each staff member’s ReportsTo to a manager’s CrewID:
SELECT Staff.Name, Manager.Name AS ManagerFROM Crew AS StaffINNER JOIN Crew AS Manager ON Staff.ReportsTo = Manager.CrewIDORDER BY Staff.CrewID;| Name | Manager |
|---|---|
| Tom Hale | Maya Okafor |
| Priya Nair | Tom Hale |
| Owen Price | Maya Okafor |
The three people whose ReportsTo is empty are left out, as an inner join leaves out any row without a partner. To list everyone, with a blank where there is no manager, make it a left join:
SELECT Staff.Name, Manager.Name AS ManagerFROM Crew AS StaffLEFT JOIN Crew AS Manager ON Staff.ReportsTo = Manager.CrewIDORDER BY Staff.CrewID;| Name | Manager |
|---|---|
| Maya Okafor | |
| Tom Hale | Maya Okafor |
| Priya Nair | Tom Hale |
| Owen Price | Maya Okafor |
| Lucy Brennan | |
| Sam Ellis |
Pairs within a group
Section titled “Pairs within a group”A self join can also pair up rows that share a value. To list every pair of people in the same department:
SELECT A.Name AS Person1, B.Name AS Person2, A.DepartmentFROM Crew AS AINNER JOIN Crew AS B ON A.Department = B.Department AND A.CrewID < B.CrewIDORDER BY A.CrewID, B.CrewID;| Person1 | Person2 | Department |
|---|---|---|
| Tom Hale | Priya Nair | Accounts |
| Tom Hale | Lucy Brennan | Accounts |
| Priya Nair | Lucy Brennan | Accounts |
The condition A.CrewID < B.CrewID does two jobs. It stops anyone being paired with themselves, and it lists each pair once rather than twice, since Tom with Priya and Priya with Tom are the same pair.