SELF JOIN

Basic SQL
≈ 1 min read

A table can be joined to itself

A SELF JOIN is an ordinary join where the same table appears twice under different aliases. It is useful when rows in one table relate to other rows in that same table.

SELECT
    e.name AS employee,
    m.name AS manager
FROM employees AS e
LEFT JOIN employees AS m ON m.id = e.manager_id;

The alias e represents the employee, while m represents the manager. Although there is only one physical table, the roles must be distinguished in the query.

Aliases are essential for clarity here

Without separate source names, it would be impossible to tell which role an id, name, or manager_id belongs to. That is why a SELF JOIN is best read as two logical copies of the same table.

SELF JOIN is not a separate SQL keyword. The name describes a technique. The actual join type is still an ordinary one such as INNER or LEFT.