skip to content

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
the top three levels of the org, from the block below. click a name to fold it. every arrow down is a 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:

join =
data =
e.manager_id ↓ m.id →1 Fatima Lopez2 Olivia Lopez3 Mei Dubois4 Chen Smith5 Rahul Singh
NULL Fatima Lopez·····
1 Olivia Lopez✓····
1 Mei Dubois✓····
1 Chen Smith✓····
2 Rahul Singh·✓···
inner join result
manager_idnameidm.name
1Olivia Lopez1Fatima Lopez
1Mei Dubois1Fatima Lopez
1Chen Smith1Fatima Lopez
2Rahul Singh2Olivia Lopez
(4 rows)

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.

model of SQL join semantics · checked against postgres 18.6
the first five employees, twice: 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:

sqldb=org
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;
output, from postgres 18.6
SELECT 13
idint4nametexttitletextmanagertext
1Fatima Lopezceonull
2Olivia LopezvpFatima Lopez
3Mei DuboisvpFatima Lopez
4Chen SmithvpFatima Lopez
5Rahul SinghdirectorOlivia Lopez
6Amelia HansendirectorOlivia Lopez
7Olivia SinghdirectorOlivia Lopez
8Noah SilvadirectorMei Dubois
9Valentina HaddaddirectorMei Dubois
10Kenji LarsendirectorMei Dubois
11Valentina OkafordirectorChen Smith
12Leila LarsendirectorChen Smith
13Chen JensendirectorChen Smith
(13 rows)

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:

sqldb=org
SELECT employees.name
FROM employees
JOIN employees ON employees.id = employees.manager_id;
output, from postgres 18.6
ERROR 42712: table name "employees" specified more than once
predict the output
sql
SELECT count(*)
FROM employees AS e
JOIN employees AS m ON m.id = e.manager_id;
sqldb=org
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;
output, from postgres 18.6
#1 · SELECT 1
inner_joinint8
299
(1 row)
#2 · SELECT 1
left_joinint8
300
(1 row)

up two levels

every extra level up is one more copy. the manager's manager is a third alias:

sqldb=org
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;
output, from postgres 18.6
SELECT 6
idint4nametextmanagertextmanagers_managertext
14Ama RossiRahul SinghOlivia Lopez
15Ingrid SmithRahul SinghOlivia Lopez
16Clara PetrovRahul SinghOlivia Lopez
17Yuna GarciaAmelia HansenOlivia Lopez
18Aisha GarciaAmelia HansenOlivia Lopez
19Kenji HansenAmelia HansenOlivia Lopez
(6 rows)

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:

ON =
query.sql
  1. 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 LopezMei DuboisChen Smith
Olivia Lopez✓✓✓
Mei Dubois✓✓✓
Chen Smith✓✓✓
pairs
9
pass ON
9
inner join result
idint4nametextidint4nametext
2Olivia Lopez2Olivia Lopez
2Olivia Lopez3Mei Dubois
2Olivia Lopez4Chen Smith
3Mei Dubois2Olivia Lopez
3Mei Dubois3Mei Dubois
3Mei Dubois4Chen Smith
4Chen Smith2Olivia Lopez
4Chen Smith3Mei Dubois
4Chen Smith4Chen Smith
(9 rows)

ON true: every vp paired with every vp, themselves included. 3 × 3 = 9.

real output, postgres 18.6 (PGlite 0.5.12) · self
the three vps against themselves. pick an ON: 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:

sqldb=org
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;
output, from postgres 18.6
#1 · SELECT 3
#2 · SELECT 1
same_name_pairsint8
65
(1 row)
#3 · SELECT 4
nametextfirst_idint4second_idint4
Clara Petrov16105
Clara Petrov16254
Clara Petrov105254
Priya Shah57203
(4 rows)

(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:

sqldb=org
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;
output, from postgres 18.6
SELECT 24
depttexttitletextpeopleint8
engineeringassociate54
engineeringlead18
engineeringmanager6
productassociate27
productlead9
productmanager3
designassociate27
designlead9
designmanager3
salesassociate54
saleslead18
salesmanager6
supportassociate16
supportlead9
supportmanager3
financeassociate0
financelead9
financemanager3
peopleassociate0
peoplelead9
(24 rows)showing 20 ·

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.id gives every pair once and nobody paired with themselves.
  • CROSS JOIN builds every combination. LEFT JOIN onto it shows the empty ones.