QA Interview Hub · Knowledge base · Quizzes · Українська

SQL › JOIN

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

e (employee)m (manager)OlenaPetroMaksIrynaOlenaPetroOne table in two roles: e and m.Olena has no manager: INNER drops her.
Figure 1. The arrow leads from an employee to their manager. Olena has no pair, because her manager_id is NULL.

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

e LEFT JOIN m
employeesalarymanagertheir salary
Olena5000NULLNULL filtered
Petro4000Olena5000 filtered
Maks5500Olena5000
Iryna3000Petro4000 filtered
WHERE e.salary > m.salary
employeesalary
Maks5500
Figure 2. LEFT JOIN is shown for clarity: with JOIN Olena's row would not exist at all, and here the comparison with NULL gives UNKNOWN, Petro and Iryna earn less than their managers. Maks remains.

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.id instead of m.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.

In an interview. Junior: A self join joins a table to itself when a row refers to another row of the same table, like an employee to a manager. The table is included twice with different aliases. LEFT JOIN is needed so the top-level boss is not lost. Middle/Senior: I read ON as a sentence: "m is the manager of e", because the direction is easy to swap and the result stays plausible. To find duplicates I add a.id < b.id to remove mirrored pairs. A self join sees one level of a hierarchy, deeper ones need a recursive CTE, and I treat a loop in the data as a defect.

More articles in this chapter