A SELF JOIN joins a table to itself using different aliases so that rows within the same table can be compared or related.
Many business datasets contain hierarchical relationships inside one table, such as employees and their managers.
Display each employee together with their manager's name.
SELECT
e.EmployeeName,
m.EmployeeName AS ManagerName
FROM Employees e
LEFT JOIN Employees m
ON e.ManagerID = m.EmployeeID;
SELF JOIN is useful for organizational hierarchies, employee-manager relationships, category hierarchies, and parent-child structures.
- A SELF JOIN joins a table to itself.
- Different aliases are required.
- It is useful for hierarchical data.
- Employees and managers are a common example.
- SELF JOIN can use INNER or OUTER JOIN types.
What is a SELF JOIN?
A SELF JOIN joins a table with itself so rows within the same table can be compared or related.
Why are aliases important in a SELF JOIN?
Aliases distinguish the different roles played by the same table in the query.