Sub topic 5
Keeping the Top of the Hierarchy with a LEFT Self Join
Prerequisites
This chapter assumes that you know basic SELECT, INNER JOIN, LEFT JOIN, ORDER BY, primary keys, foreign keys, and NULL handling. A self join is a query that joins a table to itself. It is useful when rows in one table refer to other rows in that same table.
Consider this employee hierarchy:
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
manager_id INT REFERENCES employees(id)
);
INSERT INTO employees (id, name, manager_id) VALUES
(1, 'Ava', NULL),
(2, 'Ben', 1),
(3, 'Chen', 1),
(4, 'Dana', 2);The manager_id column stores the id of another employee. Ava is at the top because her manager_id is NULL.
Why an INNER self join loses top-level rows
To display each employee and their manager, the table must play two roles:
erepresents the employee.mrepresents the manager.
An INNER JOIN returns only rows that satisfy the join condition:
SELECT e.name AS employee, m.name AS manager
FROM employees e
INNER JOIN employees m
ON e.manager_id = m.id;The condition matches an employee's manager_id with a manager's id. Ben, Chen, and Dana have matching managers, so they appear. Ava does not appear because NULL does not equal any id.
Use LEFT JOIN to preserve the hierarchy's top
A LEFT JOIN keeps every row from its left input. If no matching manager exists, columns from the right-side alias contain NULL.
SELECT
e.name AS employee,
m.name AS manager
FROM employees e
LEFT JOIN employees m
ON e.manager_id = m.id
ORDER BY e.id;The result is:
| employee | manager |
|---|---|
| Ava | NULL |
| Ben | Ava |
| Chen | Ava |
| Dana | Ben |
Ava remains in the result because employees e is the left side of the join. The missing manager is represented by m.name = NULL.
Understanding the aliases
Without aliases, SQL could not clearly distinguish the two roles. Both references point to employees, but each reference has a different purpose:
FROM employees e
LEFT JOIN employees m
ON e.manager_id = m.idThe qualified names make the direction clear:
e.manager_idis the reference stored on the employee row.m.idis the referenced manager's primary key.e.namelabels the employee.m.namelabels the manager.
The relationship is therefore read as: “Find the employee whose manager ID points to this manager ID.”
Filtering without removing the top row
Suppose you want employees managed by Ava. This query keeps the LEFT JOIN, but the WHERE condition removes rows whose manager is not Ava:
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m
ON e.manager_id = m.id
WHERE m.name = 'Ava';That behavior is expected. The WHERE clause runs after the join and rejects rows where m.name is NULL. If you want to preserve employees without managers while limiting which manager can match, put the condition in the ON clause instead:
SELECT e.name AS employee, m.name AS manager
FROM employees e
LEFT JOIN employees m
ON e.manager_id = m.id
AND m.name = 'Ava'
ORDER BY e.id;This version keeps all employees. Only Ava can be used as a matching manager; other employees receive NULL in the manager column.
Reading deeper hierarchies
A self join like this reads one parent level. It shows an employee's immediate manager, but it does not automatically show the manager's manager. Repeating self joins can handle a known, small number of levels. For unknown or many levels, a recursive common table expression is usually a better choice.
Exercise
What changes if the query uses INNER JOIN instead of LEFT JOIN in the employee-manager query, and why?
Show answer
Ava is removed because her managerid is NULL, so no row satisfies e.managerid = m.id. LEFT JOIN keeps Ava and returns NULL for her manager.