What is a self join?
A self join joins a table to itself through two aliases when a row refers to another row of the same table, such as an employee to a manager. It is an ordinary INNER or LEFT JOIN, not a separate kind. The ON direction is read as a sentence: m.id = e.manager_id means "m is the manager of e". It sees one hierarchy level; deeper ones need a recursive CTE.
SQL · JOIN
Find employees who earn more than their manager. But the manager is also a row in employees. How?
In the employees table each row has a manager_id column that points to the id of another row of the same table. To compare an employee's salary with the manager's, both rows are needed in one result row. For that the table is joined to itself. This lesson is about how to read a self join, why it is easiest to write backwards and where it is used besides hierarchies.
How it works and why. A self join is not a separate kind of JOIN but an ordinary INNER or LEFT JOIN where both sides are the same table. For the database to tell them apart, each gets its own alias, and then the table plays two roles. For example e is the employee, m the manager, and the condition m.id = e.manager_id reads as "m is the manager of e". The meaning of the query depends on the role each alias has.
One table in two roles
Example: a plausible answer, backwards. Data: Olena (5000, no manager), Petro (4000, manager Olena), Maks (5500, manager Olena), Iryna (3000, manager Petro). A query with the direction swapped:
-- wrong: ON reversed (m.manager_id = e.id), direction swapped
SELECT e.name
FROM employees e
JOIN employees m ON m.manager_id = e.id
WHERE e.salary > m.salary;
-- Olena, Petro: they earn more than their SUBORDINATES
It runs and returns two people, and that looks plausible. But m.manager_id = e.id means that e is the boss here and m the subordinate, so the query answers "who earns more than a subordinate". The report would name the wrong people: Olena and Petro instead of Maks. The right version reads "m is the manager of e":
SELECT e.name AS employee, e.salary,
m.name AS manager, m.salary AS manager_salary
FROM employees e
JOIN employees m ON m.id = e.manager_id
WHERE e.salary > m.salary;
-- Maks 5500 > Olena 5000
Self join and the salary filter
| employee | salary | manager | their salary |
|---|---|---|---|
| Olena | 5000 | NULL | NULL filtered |
| Petro | 4000 | Olena | 5000 filtered |
| Maks | 5500 | Olena | 5000 |
| Iryna | 3000 | Petro | 4000 filtered |
| employee | salary |
|---|---|
| Maks | 5500 |
A practical check: before adding the filter, output both sides (e.name, m.name) and read a few rows aloud: "employee Petro, manager Olena". If the sentence is wrong, the ON is written backwards.
Limits and alternatives. If you do not need the manager's whole row but only the fact that one exists, EXISTS is enough. Two more cases are typical for a self join. The first: finding pairs of equal values, for example duplicate emails:
-- pairs of users with the same email
SELECT a.id AS id1, b.id AS id2, a.email
FROM users a
JOIN users b ON b.email = a.email AND a.id < b.id;
-- a.id < b.id: each pair once, no pair with itself
The condition a.id < b.id does two jobs: it removes the pair of a row with itself and keeps each pair once rather than in both directions (a, b) and (b, a). Without it the result would be twice as large and would contain "duplicates" that are merely mirrors. For large tables it is faster to group by email and take HAVING COUNT(*) > 1, but a self join shows both identifiers side by side. The second case: hierarchies. A self join climbs one level (an employee and their manager). For any depth, for example the whole chain up to the director, a recursive query is needed:
-- the whole hierarchy, any depth
WITH RECURSIVE chain AS (
SELECT id, name, manager_id, 1 AS lvl
FROM employees WHERE manager_id IS NULL
UNION ALL
SELECT e.id, e.name, e.manager_id, c.lvl + 1
FROM employees e
JOIN chain c ON e.manager_id = c.id
)
SELECT name, lvl FROM chain ORDER BY lvl;
Recursive CTEs exist in PostgreSQL and MySQL 8 but need care: if reporting loops in the data (A manages B, B manages A), those people silently drop out of the report: the walk from roots with manager_id IS NULL never reaches them. Infinite recursion comes from walking up from an employee or from a many-parent graph: MySQL stops it at cte_max_recursion_depth (1000 by default), PostgreSQL has the CYCLE clause. A loop in the data is itself a defect and is found with a separate check, for example WHERE id = manager_id for the simplest case. The top level needs a LEFT JOIN, because INNER JOIN, as we saw, drops a person with no manager.
Common mistakes.
- Not giving the table aliases: the database rejects the query or the columns get mixed up.
- Swapping the ON direction (
m.manager_id = e.idinstead ofm.id = e.manager_id): the query answers another question and the result looks plausible. - INNER JOIN where the top-level boss is needed: a person with no manager vanishes.
- Searching for pairs without
a.id < b.id: each row matches itself and pairs repeat as mirrors. - Expecting the whole hierarchy from a self join: it sees only one level.
Check yourself
employees has 1000 rows and 1 of them has manager_id = NULL. How many rows do INNER JOIN and LEFT JOIN return with m.id = e.manager_id?
Answer
INNER: 999, because the employee with no manager finds no pair. LEFT: 1000, and the first row has NULL in the m columns. This assumes every manager_id points to an existing employee.
A user email occurs three times. How many rows does JOIN users b ON b.email = a.email AND a.id < b.id return for that email?
Answer
Three rows: the pairs (1,2), (1,3), (2,3), that is C(3,2). Without a.id < b.id there would be 9 rows: 3 × 3, including each row paired with itself and the mirrored pairs.