self joins and CROSS JOIN
a table joined to itself to find each employee's manager, and every pair of rows on purpose.
- address
- everything.joins.self_and_cross_joins
- part
- part 3, joins and subqueries
- chapter
- chapter 4 of 11
- reading time
- 8 min
a self join is a table joined to itself under two aliases, so a row can meet another row of the same table: an employee and their manager, two people with the same name. nothing about it is special. it's an ordinary join where both sides happen to be one table.
a CROSS JOIN pairs every row with every row, on purpose: grids, combinations, every department against every job title.
the picture
you know how employees has a manager_id column, and the manager it points at is... also in employees? the org dataset is one table that's a whole tree: Fatima Lopez at the top, three reports under every manager, six levels down to 300 people.
- ceo, id 1, manager_id NULL
- ├── vp, id 2
- │ ├── Rahul Singhdirector, id 5
- │ ├── Amelia Hansendirector, id 6
- │ └── Olivia Singhdirector, id 7
- ├── vp, id 3
- │ ├── Noah Silvadirector, id 8
- │ ├── Valentina Haddaddirector, id 9
- │ └── Kenji Larsendirector, id 10
- └── vp, id 4
- ├── Valentina Okafordirector, id 11
- ├── Leila Larsendirector, id 12
- └── Chen Jensendirector, id 13
manager_id pointing back up at an id in the same table.think of a printed staff list where every line ends with "reports to: line 2". to write the boss's name next to each person, you'd open a second copy of the same list and look the number up there. that's the whole trick: two copies, two names for them.
two copies of one table
the two copies get two aliases, here e for the employee and m for the manager. after that, postgres treats them as two tables that happen to have the same rows:
| e.manager_id ↓ m.id → | 1 Fatima Lopez | 2 Olivia Lopez | 3 Mei Dubois | 4 Chen Smith | 5 Rahul Singh |
|---|---|---|---|---|---|
| NULL Fatima Lopez | · | · | · | · | · |
| 1 Olivia Lopez | ✓ | · | · | · | · |
| 1 Mei Dubois | ✓ | · | · | · | · |
| 1 Chen Smith | ✓ | · | · | · | · |
| 2 Rahul Singh | · | ✓ | · | · | · |
| manager_id | name | id | m.name |
|---|---|---|---|
| 1 | Olivia Lopez | 1 | Fatima Lopez |
| 1 | Mei Dubois | 1 | Fatima Lopez |
| 1 | Chen Smith | 1 | Fatima Lopez |
| 2 | Rahul Singh | 2 | Olivia Lopez |
4 pairs satisfy ON, so 4 rows. a key that appears twice on each side matches 2 × 2 = 4 times, and NULL matches nothing, not even NULL.
e down the side by their manager_id, m across the top by id. inner drops Fatima Lopez, who has no manager. left keeps her, padded.for real, the top of the org with each manager's name. a LEFT JOIN, so the CEO isn't lost:
SELECT e.id, e.name, e.title, m.name AS manager
FROM employees AS e
LEFT JOIN employees AS m ON m.id = e.manager_id
WHERE e.id <= 13
ORDER BY e.id;| idint4 | nametext | titletext | managertext |
|---|---|---|---|
| 1 | Fatima Lopez | ceo | null |
| 2 | Olivia Lopez | vp | Fatima Lopez |
| 3 | Mei Dubois | vp | Fatima Lopez |
| 4 | Chen Smith | vp | Fatima Lopez |
| 5 | Rahul Singh | director | Olivia Lopez |
| 6 | Amelia Hansen | director | Olivia Lopez |
| 7 | Olivia Singh | director | Olivia Lopez |
| 8 | Noah Silva | director | Mei Dubois |
| 9 | Valentina Haddad | director | Mei Dubois |
| 10 | Kenji Larsen | director | Mei Dubois |
| 11 | Valentina Okafor | director | Chen Smith |
| 12 | Leila Larsen | director | Chen Smith |
| 13 | Chen Jensen | director | Chen Smith |
the aliases aren't optional here. without them, postgres has two tables called employees in one FROM and no way to tell which name you mean, so it refuses:
SELECT employees.name
FROM employees
JOIN employees ON employees.id = employees.manager_id;SELECT count(*)
FROM employees AS e
JOIN employees AS m ON m.id = e.manager_id;SELECT count(*) AS inner_join FROM employees AS e JOIN employees AS m ON m.id = e.manager_id;
SELECT count(*) AS left_join FROM employees AS e LEFT JOIN employees AS m ON m.id = e.manager_id;| inner_joinint8 |
|---|
| 299 |
| left_joinint8 |
|---|
| 300 |
up two levels
every extra level up is one more copy. the manager's manager is a third alias:
SELECT e.id, e.name, m.name AS manager, gm.name AS managers_manager
FROM employees AS e
JOIN employees AS m ON m.id = e.manager_id
JOIN employees AS gm ON gm.id = m.manager_id
WHERE e.id BETWEEN 14 AND 19
ORDER BY e.id;| idint4 | nametext | managertext | managers_managertext |
|---|---|---|---|
| 14 | Ama Rossi | Rahul Singh | Olivia Lopez |
| 15 | Ingrid Smith | Rahul Singh | Olivia Lopez |
| 16 | Clara Petrov | Rahul Singh | Olivia Lopez |
| 17 | Yuna Garcia | Amelia Hansen | Olivia Lopez |
| 18 | Aisha Garcia | Amelia Hansen | Olivia Lopez |
| 19 | Kenji Hansen | Amelia Hansen | Olivia Lopez |
this works for a fixed number of levels. "everyone above Ama Rossi, however many there are" can't be written as a fixed number of joins, because you don't know how many to write. that's a query that has to repeat itself until it runs out of rows, a recursive CTE.
pairs within one table
the other use of a self join: comparing rows of a table with each other. take the three vice presidents, and join them to themselves:
- 1SELECT a.id, a.name, b.id, b.name FROM vps AS a JOIN vps AS b ON true ORDER BY a.id, b.id;
| a ↓ b → | Olivia Lopez | Mei Dubois | Chen Smith |
|---|---|---|---|
| Olivia Lopez | ✓ | ✓ | ✓ |
| Mei Dubois | ✓ | ✓ | ✓ |
| Chen Smith | ✓ | ✓ | ✓ |
| idint4 | nametext | idint4 | nametext |
|---|---|---|---|
| 2 | Olivia Lopez | 2 | Olivia Lopez |
| 2 | Olivia Lopez | 3 | Mei Dubois |
| 2 | Olivia Lopez | 4 | Chen Smith |
| 3 | Mei Dubois | 2 | Olivia Lopez |
| 3 | Mei Dubois | 3 | Mei Dubois |
| 3 | Mei Dubois | 4 | Chen Smith |
| 4 | Chen Smith | 2 | Olivia Lopez |
| 4 | Chen Smith | 3 | Mei Dubois |
| 4 | Chen Smith | 4 | Chen Smith |
ON true: every vp paired with every vp, themselves included. 3 × 3 = 9.
true pairs everyone with everyone, themselves included. <> drops the diagonal. < keeps one triangle: every pair once.a.id < b.id is the move to remember. with <> every pair shows up twice, as (Olivia, Mei) and (Mei, Olivia). with < only the copy where the smaller id comes first survives, so n rows make n × (n − 1) / 2 pairs. it's how you find duplicates. 300 employees, and some names repeat:
CREATE TABLE vps AS SELECT id, name, salary FROM employees WHERE title = 'vp';
SELECT count(*) AS same_name_pairs
FROM employees AS a
JOIN employees AS b ON b.name = a.name AND a.id < b.id;
SELECT a.name, a.id AS first_id, b.id AS second_id
FROM employees AS a
JOIN employees AS b ON b.name = a.name AND a.id < b.id
WHERE a.name IN ('Priya Shah', 'Clara Petrov')
ORDER BY a.name, a.id, b.id;| same_name_pairsint8 |
|---|
| 65 |
| nametext | first_idint4 | second_idint4 |
|---|---|---|
| Clara Petrov | 16 | 105 |
| Clara Petrov | 16 | 254 |
| Clara Petrov | 105 | 254 |
| Priya Shah | 57 | 203 |
(the first statement makes the vps table from the figure, if you want to play with it.) Clara Petrov is three people, so she makes three pairs: 3 × 2 / 2.
CROSS JOIN, on purpose
a CROSS JOIN has no ON. it's the whole grid, every row of one side with every row of the other. by accident it's a disaster: forget a join condition in a comma join and 300 employees become 90,000 rows. on purpose, it's how you build the rows that should exist, so that the ones nobody filled in still show up.
a headcount report: every department, for three job titles, even where the answer is 0. the CROSS JOIN builds the 8 × 3 grid, then a LEFT JOIN fills in the people:
SELECT d.name AS dept, t.title, count(e.id) AS people
FROM departments AS d
CROSS JOIN (VALUES ('manager'), ('lead'), ('associate')) AS t (title)
LEFT JOIN employees AS e ON e.dept_id = d.id AND e.title = t.title
GROUP BY d.id, d.name, t.title
ORDER BY d.id, t.title;| depttext | titletext | peopleint8 |
|---|---|---|
| engineering | associate | 54 |
| engineering | lead | 18 |
| engineering | manager | 6 |
| product | associate | 27 |
| product | lead | 9 |
| product | manager | 3 |
| design | associate | 27 |
| design | lead | 9 |
| design | manager | 3 |
| sales | associate | 54 |
| sales | lead | 18 |
| sales | manager | 6 |
| support | associate | 16 |
| support | lead | 9 |
| support | manager | 3 |
| finance | associate | 0 |
| finance | lead | 9 |
| finance | manager | 3 |
| people | associate | 0 |
| people | lead | 9 |
24 rows, and research's three rows say 0: the department exists, nobody works in it. (finance and people have no associates either: the tree's last level runs out at employee 300 before it gets to them.) a plain join from employees could never show that, because there's no employee to start from. (VALUES is a table written inline. it can go anywhere a table can.)
the org dataset itself was built this way: its on-call rota is a CROSS JOIN of seven days with two engineers. calendars, sizes × colours, every student × every course: whenever the question is "every combination", the answer starts with CROSS JOIN.
keylines
- a self join is a normal join with the same table on both sides, under two aliases.
- employee → manager is a join on
m.id = e.manager_id. the root of the tree needs a LEFT JOIN. - each level up is one more alias. any number of levels needs a recursive CTE.
a.id < b.idgives every pair once and nobody paired with themselves.- CROSS JOIN builds every combination. LEFT JOIN onto it shows the empty ones.