Skip to content

SQL Self Join

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.column
FROM table_name AS a
INNER 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.

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 Manager
FROM Crew AS Staff
INNER JOIN Crew AS Manager ON Staff.ReportsTo = Manager.CrewID
ORDER 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 Manager
FROM Crew AS Staff
LEFT JOIN Crew AS Manager ON Staff.ReportsTo = Manager.CrewID
ORDER BY Staff.CrewID;
Name Manager
Maya Okafor
Tom Hale Maya Okafor
Priya Nair Tom Hale
Owen Price Maya Okafor
Lucy Brennan
Sam Ellis

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.Department
FROM Crew AS A
INNER JOIN Crew AS B ON A.Department = B.Department AND A.CrewID < B.CrewID
ORDER 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.