Sub topic 3
Self joins: treating one table as two
This chapter assumes you can write SELECT, WHERE, and ORDER BY. It also assumes you know INNER JOIN and LEFT JOIN with an ON condition, primary and foreign keys, and how NULL behaves in comparisons. You have already seen why a table that appears twice in a query needs aliases. Here you use them to build your first self join and learn how the database evaluates it.
What a self join is
A self join is a normal join in which both sides are the same table. SQL has no SELF JOIN keyword. You write INNER JOIN or LEFT JOIN, name the same table twice, and give each mention its own alias.
You need a self join when a row holds a reference to another row of the same table. The standard case is a table with a foreign key that points to its own primary key. Each employee row stores the id of the employee's manager, and that manager is also a row in the same table.
The sample data
All examples in this chapter use one table. The manager_id column is a foreign key to employees(id).
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 table contains this data:
| id | name | manager_id |
|---|---|---|
| 1 | Ava | NULL |
| 2 | Ben | 1 |
| 3 | Chen | 1 |
| 4 | Dana | 2 |
Ava has no manager, so her manager_id is NULL. Ben and Chen report to Ava. Dana reports to Ben.
The question "who is each person's manager?" cannot be answered from one row. Ben's row says only manager_id = 1. To turn that 1 into the name Ava, you must find the row whose id is 1, and that row is in the same table.
Thinking of one table as two
Picture the query working on two copies of employees. One copy plays the role of the employee, and the other plays the role of the manager. Nothing is copied on disk. The aliases give the query two independent handles on the same data.
SELECT e.name AS employee, m.name AS manager
FROM employees e
INNER JOIN employees m ON e.manager_id = m.id;Read it in three parts:
employees eis the employee role. Each of its rows is one person we are describing.employees mis the manager role. For each employee, the database looks here for a row to match.ON e.manager_id = m.idlinks the roles. The employee's foreign key must equal the manager's primary key.
The result has three rows:
| employee | manager |
|---|---|
| Ben | Ava |
| Chen | Ava |
| Dana | Ben |
Ava is missing, and the next section explains why.
Ben appears twice in the diagram. He is an e row for the first arrow and an m row for Dana's arrow. The same physical row plays both roles, which is why one table can describe both employees and managers.
How the database evaluates it
Conceptually, the database takes each row of e and looks for rows of m where the ON condition is true.
| e row | e.manager_id | Matching m row | Kept? |
|---|---|---|---|
| Ava (1) | NULL | none, because `NULL = id` is never true | No |
| Ben (2) | 1 | Ava (1) | Yes |
| Chen (3) | 1 | Ava (1) | Yes |
| Dana (4) | 2 | Ben (2) | Yes |
Ava is dropped because comparing NULL to anything gives unknown, not true. An INNER JOIN keeps a row only when the condition is true. This is usually not what you want in a report, and the next chapter fixes it with a LEFT JOIN.
The planner does not copy the table. It may scan the table twice, or, more often, scan one side and use the primary key index on id to find each match on the other side. Because m.id is a primary key, each employee matches at most one manager. The result therefore never has more rows than the e side.
Why the aliases are required
The database must tell the two roles apart. Without aliases, it cannot. In PostgreSQL, this query fails:
SELECT name
FROM employees
INNER JOIN employees ON manager_id = id;PostgreSQL reports ERROR: table name "employees" specified more than once. Other databases give a similar message about a duplicate table name or an ambiguous column. The fix is to give each mention of the table its own alias and qualify every column that exists in both roles.
Qualify every column, even when the engine would accept an unqualified one. Both roles have id, name, and manager_id, so almost every column name in a self join is ambiguous. Writing e.name and m.name also makes the query readable. Short aliases such as e and m work, but the role names emp and mgr read better in larger queries.
Choosing the direction of the ON condition
The ON condition decides which alias is the parent and which is the child. Reversing it gives a valid query with a different meaning:
SELECT e.name AS employee, m.name AS manager
FROM employees e
INNER JOIN employees m ON e.id = m.manager_id;This returns Ava with Ben, Ava with Chen, and Ben with Dana. The column labels now lie, because e is the manager and m is the report. The query does not fail, so you get no error. You get wrong data under correct-looking headers.
A habit that prevents this is to put the foreign key on the child side and the primary key on the parent side: child.parent_id = parent.id. Then check the first row of your output against the raw table.
A second mistake is joining a key to itself:
SELECT e.name AS employee, m.name AS manager
FROM employees e
INNER JOIN employees m ON e.id = m.id;Each row matches only itself, so you get four rows where every person is their own "manager". This usually happens when someone types id on both sides out of habit. The row count is a useful clue. A self join through a foreign key should not return exactly one row per table row with identical names on both sides.
Inspecting both roles side by side
When a self join gives a surprising result, show every column from both aliases and rename the duplicates so you can tell them apart:
SELECT e.id AS emp_id, e.name AS emp_name, e.manager_id,
m.id AS mgr_id, m.name AS mgr_name
FROM employees e
INNER JOIN employees m ON e.manager_id = m.id
ORDER BY e.id;For the sample data, emp_id 2 shows manager_id 1 and mgr_id 1. The two numbers must agree in every row, because they are the two sides of the ON condition. If they disagree, the condition is not what you think it is.
Adding conditions
Self joins accept WHERE clauses like any other join. Use the alias to say which role you are filtering:
SELECT e.name AS employee, m.name AS manager
FROM employees e
INNER JOIN employees m ON e.manager_id = m.id
WHERE m.name = 'Ava'
ORDER BY e.name;This returns Ben and Chen, the people who report directly to Ava. Filtering on e.name = 'Ava' would return nothing, because Ava is not an employee with a manager in the inner join result.
For an INNER JOIN, a condition in WHERE and the same condition added to ON give the same rows. That equivalence stops holding once you use outer joins, which is one reason to keep link conditions in ON and filters in WHERE.
Edge cases to know
- Cycles. A foreign key to the same table allows an employee to be their own manager, or two people to manage each other. A one-level self join returns such rows without complaint. The database constraint only checks that the referenced id exists.
- Self-reference. A row with
manager_id = idis its own manager and matches itself. If your data should not contain these, find them withWHERE e.id = e.manager_id. - Dangling keys. The foreign key constraint normally prevents a
manager_idthat points to a missing row. If the constraint is absent, anINNER JOINsilently drops such rows, just as it dropsNULLmanagers. - Depth. One self join looks up exactly one level. To get the manager's manager, you need a second self join with a third alias. Each extra level adds another join, which is why unbounded hierarchies need a different tool, covered at the end of this tutorial.
- Duplicates. If the column you join on is not unique on the parent side, one employee can match several rows. Joining on a primary key avoids this.
Summary of the working model
- Name the same table twice and give each mention an alias.
- Treat each alias as an independent role, with its own rows and columns.
- Write an
ONcondition that links the child's foreign key to the parent's primary key. - Qualify every column with its alias.
- Check the output against the raw table, and remember that an inner join drops rows with no match.
Exercise
Using the employees table from this chapter, write a query that lists each employee who has a manager, along with the manager's id and name. Name the output columns employee, manager_id, and manager. What rows does it return?
Show answer
SELECT e.name AS employee, m.id AS managerid, m.name AS manager FROM employees e INNER JOIN employees m ON e.managerid = m.id ORDER BY e.id; It returns three rows: (Ben, 1, Ava), (Chen, 1, Ava), and (Dana, 2, Ben). Ava is not returned because her manager_id is NULL, and NULL = m.id is never true.
Exercise
A teammate writes ON e.id = m.manager_id and labels the columns employee and manager. What does the query actually return, and why is it misleading?
Show answer
It returns (Ava, Ben), (Ava, Chen), and (Ben, Dana). The condition makes e the parent and m the child, so the column labelled employee holds managers and the column labelled manager holds their direct reports. The query runs without error, so only checking the output against the source table reveals the mistake. The fix is ON e.manager_id = m.id.