Sub topic 11
Joining a Table to Itself
This chapter covers self joins: how to write one, what it returns, and where it goes wrong. It assumes you can write an INNER JOIN ... ON query, use table aliases, and know how primary and foreign keys work. If any of that is unfamiliar, review the earlier chapters on aliases and join conditions first.
What a self join is
A self join is an ordinary join in which both sides are the same table. SQL has no SELF JOIN keyword. You list the table twice in the FROM clause and give each occurrence a different alias. The database treats the two aliases as two independent copies of the rows, and the ON condition decides which row from copy one pairs with which row from copy two.
Self joins are useful when a table holds a relationship between its own rows. Common cases:
- An employee table where each row points to its manager, who is another row in the same table.
- A category table where each category points to a parent category.
- A table of events or readings where you compare each row with another row, such as one with a later date.
- A table where you look for pairs of rows that share a value, such as two customers in the same city.
The employee and manager example
The standard example is a hierarchy stored in one table. Each employee has a manager_id that refers to the id of another employee. This is a foreign key that points back to its own table.
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL,
manager_id INTEGER REFERENCES employees (id)
);
SELECT e.name AS employee, m.name AS manager
FROM employees AS e
INNER JOIN employees AS m ON m.id = e.manager_id;Read the query by giving each alias a role:
eis the employee. Its rows supply thenameand themanager_id.mis the manager. Its rows are looked up byid.- The condition
m.id = e.manager_idsays: for each employee, find the row whoseidequals that employee'smanager_id.
Without aliases, a column such as name or id would be ambiguous, because both copies have it. The database would reject the query. The aliases are required, not just a convenience.
A worked trace
Suppose the table contains these rows:
| id | name | manager_id |
|---|---|---|
| 1 | Grace | NULL |
| 2 | Alan | 1 |
| 3 | Edsger | 1 |
| 4 | Barbara | 2 |
The join compares each e row with the m rows:
- Grace (
manager_idis NULL):m.id = NULLis never true, so Grace has no match and is dropped. - Alan (
manager_id= 1): matches the row withid1, Grace. - Edsger (
manager_id= 1): matches Grace. - Barbara (
manager_id= 2): matches Alan.
The result has three rows:
| employee | manager |
|---|---|
| Alan | Grace |
| Edsger | Grace |
| Barbara | Alan |
Grace, the top of the hierarchy, is missing. This is the NULL behavior from the earlier chapter, applied to a single table. An inner join keeps only employees who have a manager. To list everyone, including people with no manager, you need an outer join, covered in a later chapter.
Running the example
This script creates the table, loads the rows from the trace, and runs the join. It runs as shown in PostgreSQL, MySQL, or SQLite.
CREATE TABLE employees (
id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL,
manager_id INTEGER REFERENCES employees (id)
);
INSERT INTO employees (id, name, manager_id) VALUES
(1, 'Grace', NULL),
(2, 'Alan', 1),
(3, 'Edsger', 1),
(4, 'Barbara', 2);
SELECT e.name AS employee, m.name AS manager
FROM employees AS e
INNER JOIN employees AS m ON m.id = e.manager_id
ORDER BY e.id;The rows must be inserted so that each manager exists before the employee refers to them, or the foreign key check fails. Here Grace comes first. Her manager_id is NULL, so she needs no parent.
Going one level further
A self join reaches one level of the hierarchy. To show an employee, their manager, and their manager's manager, join the table a third time with a third alias.
SELECT e.name AS employee,
m.name AS manager,
g.name AS grand_manager
FROM employees AS e
INNER JOIN employees AS m ON m.id = e.manager_id
INNER JOIN employees AS g ON g.id = m.manager_id;With the sample data, only Barbara appears, as Barbara, Alan, Grace. Alan's manager is Grace, but Grace has no manager, so the second join drops Alan. Each extra level removes the people near the top.
Joining a fixed number of times works only when you know the depth in advance. For arbitrary depth, SQL provides recursive common table expressions (WITH RECURSIVE). That is a separate topic, but it is the tool to reach for when a hierarchy has unknown depth.
Finding pairs within the same table
Self joins are not limited to parent and child links. They can also compare rows that share an attribute. Suppose you want pairs of employees who report to the same manager:
SELECT a.name AS first_employee, b.name AS second_employee
FROM employees AS a
INNER JOIN employees AS b
ON a.manager_id = b.manager_id
AND a.id < b.id;The second condition, a.id < b.id, solves two problems:
- It removes rows where a row pairs with itself. Every row matches itself on
manager_id, so without a filter, Alan would be paired with Alan. - It removes mirrored duplicates. Without it, you would get both (Alan, Edsger) and (Edsger, Alan). Requiring the smaller
idon the left keeps one copy of each pair.
With the sample data, the result is one row: Alan and Edsger, who both report to Grace. Grace's NULL manager_id never matches anything, so she is excluded from pairs.
The < condition is a non-equality join condition. It works because an ON clause can hold any boolean expression, which is the topic of the next chapter.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Omitting an alias on the second copy | Error such as "table name specified more than once" | Give each occurrence its own alias |
| Leaving a column unqualified | Error such as "column reference is ambiguous" | Write `e.name`, not `name` |
| Swapping the sides of the condition | Result shows managers where employees should be, or the reverse | Decide which alias is the child (holds the foreign key) and which is the parent (holds the primary key) |
| Forgetting the self-pair filter in a pairs query | Every row pairs with itself, and pairs appear twice | Add `a.id < b.id` |
| Expecting top-level rows | The root of the hierarchy is missing | Use an outer join, or accept that an inner join drops rows with NULL keys |
Swapped sides are the easiest error to make. Check the direction by reading the condition aloud: "the manager's id equals the employee's manager_id." If the roles are reversed, the query still runs and returns plausible-looking rows, but the employee and manager columns are exchanged.
Performance note
The database does not copy the table. It reads the same table through two aliases, and the usual join rules apply. The lookup column on the parent side is normally the primary key, so it is already indexed. The foreign key column, such as manager_id, is often not indexed automatically. In PostgreSQL, for example, defining a foreign key does not create an index on it. If you join or look up by manager_id often on a large table, consider adding one.
CREATE INDEX idx_employees_manager_id ON employees (manager_id);Exercise
Using the employees table from this chapter, write a query that lists each employee's name and their manager's name, but only for employees whose manager is Alan. What rows does it return with the sample data, and why is Grace not in the output?
Show answer
SELECT e.name AS employee, m.name AS manager FROM employees AS e INNER JOIN employees AS m ON m.id = e.managerid WHERE m.name = 'Alan'; It returns one row: Barbara, Alan. Grace is not in the output for two reasons: her managerid is NULL, so the join condition never matches and her row is dropped, and even if she matched, her manager is not Alan.
Exercise
Write a query that returns each pair of employees who share the same manager, once per pair, using the employees table. Explain what would go wrong if you replaced a.id < b.id with a.id <> b.id.
Show answer
SELECT a.name AS firstemployee, b.name AS secondemployee FROM employees AS a INNER JOIN employees AS b ON a.managerid = b.managerid AND a.id < b.id; With <>, the self pairs are removed but each pair appears twice, once in each order, so (Alan, Edsger) and (Edsger, Alan) would both be returned.