skip to content

joins, in one picture

a join is a filtered cross product. why the venn diagram lies to you.

address
everything.joins.joins_in_one_picture
part
part 3, joins and subqueries
chapter
chapter 1 of 11
reading time
10 min

a join is a cross product with a filter: pair every row of one table with every row of the other, then keep the pairs where ON is true. an outer join then puts back the rows that found no partner at all, padded with NULLs.

that's every join there is. the venn diagram on the cheat sheet is a picture of something else.

the picture

you know the venn diagram on every join cheat sheet? two circles, the overlap shaded for INNER, the whole left circle for LEFT. it looks tidy, it's easy to remember, and it's wrong in ways that will cost you a wrong total one day.

here's the picture that's right. think of a speed-dating night. every customer sits down once across from every store (that's the cross product). each pair answers one question, say "are we in the same city?" (that's the ON). INNER JOIN goes home with the pairs that said yes. LEFT JOIN also sends home every customer who never got a single yes, alone, with an empty chair where a partner would be (NULLs).

join =
data =
customers.city ↓ stores.city →London sohoParis maraisBerlin mitteNULL online
London Ada✓···
London Alan✓···
Paris Grace·✓··
NULL Edsger····
inner join result
namecitystores.citystore
AdaLondonLondonsoho
AlanLondonLondonsoho
GraceParisParismarais
(3 rows)

3 pairs satisfy ON, so 3 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
four customers, four stores, every pair of them. switch the join type, then press add a duplicate key: a second London store meets both Londoners, so London goes from 2 rows to 2 × 2. rows that matched nobody come back padded.

that grid is the whole chapter. the rest is taking it apart, and then showing what the circles get wrong.

every pair first

here are the two tables from the figure, for real. Edsger has no city, and the online store has no city either.

sqlempty db · session tiny
CREATE TABLE customers (name text, city text);
INSERT INTO customers VALUES ('Ada', 'London'), ('Alan', 'London'), ('Grace', 'Paris'), ('Edsger', NULL);
CREATE TABLE stores (city text, store text);
INSERT INTO stores VALUES ('London', 'soho'), ('Paris', 'marais'), ('Berlin', 'mitte'), (NULL, 'online');
output, from postgres 18.6
#1 · CREATE TABLE
#2 · INSERT 0 4
#3 · CREATE TABLE
#4 · INSERT 0 4

CROSS JOIN is the join with no filter at all. every customer, next to every store:

sqlempty db · session tiny
continues session tiny (1 earlier block run first)
SELECT c.name, c.city, s.city, s.store
FROM customers AS c CROSS JOIN stores AS s
ORDER BY c.name, s.store;
output, from postgres 18.6
SELECT 16
nametextcitytextcitytextstoretext
AdaLondonParismarais
AdaLondonBerlinmitte
AdaLondonnullonline
AdaLondonLondonsoho
AlanLondonParismarais
AlanLondonBerlinmitte
AlanLondonnullonline
AlanLondonLondonsoho
(16 rows)showing 8 ·

16 rows: 4 × 4. that's the cross product (also called the Cartesian product), and every join starts from it, at least on paper. (AS c gives the table a short name for the rest of the query. both tables have a city, so every column gets its table's name in front.)

then ON throws pairs out

an ON isn't a lookup ("go find the matching row"). it's a test, and every pair in the grid takes it. pairs where it comes out true stay. pairs where it's false, or unknown, go.

ON =
join =
query.sql
  1. 1SELECT c.name, c.city, s.city, s.store FROM customers AS c JOIN stores AS s ON s.city = c.city ORDER BY c.name, s.store;
customers ↓ stores →sohomaraismitteonline
Ada✓···
Alan✓···
Grace·✓··
Edsger····
pairs
16
pass ON
3
padded
0
inner join result
nametextcitytextcitytextstoretext
AdaLondonLondonsoho
AlanLondonLondonsoho
GraceParisParismarais
(3 rows)

the equi-join: a pair survives when the cities are equal. Edsger's NULL equals nothing, not even the online store's NULL.

real output, postgres 18.6 (PGlite 0.5.12) · on-grid
pick an ON. the grid never changes size, only which pairs pass. then switch to left: a customer whose whole row is empty comes back once, padded with NULLs, whatever the ON was.

ON true keeps all 16 pairs, which is why CROSS JOIN and JOIN ... ON true are the same query. ON false keeps none. and the ON can test anything at all: columns from both sides, a column from one side only, a constant. the common case, an = between a column on each side, has a name, the equi-join, and it's the only kind the venn diagram even tries to draw.

the one you'll write most days:

sqlempty db · session tiny
continues session tiny (2 earlier blocks run first)
SELECT c.name, c.city, s.city, s.store
FROM customers AS c JOIN stores AS s ON s.city = c.city
ORDER BY c.name, s.store;
output, from postgres 18.6
SELECT 3
nametextcitytextcitytextstoretext
AdaLondonLondonsoho
AlanLondonLondonsoho
GraceParisParismarais
(3 rows)

(JOIN on its own means INNER JOIN. the next chapter, INNER JOIN, has the spellings.)

and look who's missing: Edsger, and the online store. both cities are NULL, and NULL = NULL isn't true, it's unknown (NULL and three-valued logic has why). unknown fails the test like false does. two missing cities are not the same city.

then outer joins put back the leftovers

an outer join is the inner join plus a second pass. after the filter, look for rows that passed with nobody, and bring each one back once, with NULLs in the other table's columns:

LEFT JOIN
the pairs that passed, plus every left row that passed with no one
RIGHT JOIN
the pairs that passed, plus every right row that passed with no one
FULL JOIN
the pairs that passed, plus the leftovers from both sides

so the row count is plain arithmetic: pairs that passed + leftovers. here that's 3 + 1 for LEFT, 3 + 2 for RIGHT, and 3 + 1 + 2 for FULL:

sqlempty db · session tiny
continues session tiny (3 earlier blocks run first)
SELECT c.name, c.city, s.city, s.store
FROM customers AS c FULL JOIN stores AS s ON s.city = c.city
ORDER BY c.name, s.store;
output, from postgres 18.6
SELECT 6
nametextcitytextcitytextstoretext
AdaLondonLondonsoho
AlanLondonLondonsoho
Edsgernullnullnull
GraceParisParismarais
nullnullBerlinmitte
nullnullnullonline
(6 rows)

the NULL-padded rows aren't data anyone stored. they're the join saying "nobody". LEFT, RIGHT and FULL joins is about living with them, including the WHERE that quietly turns a LEFT JOIN back into an inner one.

predict the output
sql
INSERT INTO stores VALUES ('London', 'camden');
 
SELECT c.name, s.store
FROM customers AS c JOIN stores AS s ON s.city = c.city;

the same thing, run:

sqlempty db · session tiny
continues session tiny (4 earlier blocks run first)
INSERT INTO stores VALUES ('London', 'camden');
 
SELECT c.name, s.store
FROM customers AS c JOIN stores AS s ON s.city = c.city
ORDER BY c.name, s.store;
output, from postgres 18.6
#1 · INSERT 0 1
#2 · SELECT 5
nametextstoretext
Adacamden
Adasoho
Alancamden
Alansoho
Gracemarais
(5 rows)

why the venn diagram lies

now take the cheat sheet's picture to real data: the shop's 200 products and its 24,942 order lines. a venn diagram draws each table as a circle and a join as some shaded part of them. so the picture makes promises before you've run anything. an overlap can't be bigger than either circle. a whole circle is exactly its own size.

query =
products200 rowsorder_items24,942 rows
the picture shades
the overlap: part of each circle
so it promises
at most 200 rows
postgres returned
24,942 rows
one row is
a product glued to an order line, 14 columns wide
the picture lies, by 125x.

the overlap holds 24,942 rows, out of a circle with 200 in it. each order line pairs with its product, so a product that sold often is in a lot of rows: the chef's knife alone is in 1,826.

real output, postgres 18.6 (PGlite 0.5.12) · venn
pick a query. the bound under the diagram follows from the picture alone. the count is what postgres returned. the joins break the picture by 125x. the set operations keep it.

three lies, then:

  1. duplicates multiply. a circle's overlap can't hold more than the smaller circle, but a join can be bigger than both tables. one product with 1,826 order lines is 1,826 rows. two duplicates on each side of a key are 4 rows. sum anything over that and you count it again and again, which is a whole chapter: join fan-out.
  2. an outer join isn't a union. the shaded left circle suggests "the products, and maybe some more". a LEFT JOIN row is a product glued to an order line, or to a row of NULLs, and there are 24,943 of them, not 200.
  3. circles hold one kind of thing. a venn diagram is about sets of the same kind of element, which is exactly what INTERSECT, UNION and EXCEPT combine: rows of the same shape, stacked or compared. that's the one place the picture works. UNION, INTERSECT and EXCEPT has it.

the counts, for real:

sqldb=shop
SELECT count(*) FROM products;
SELECT count(*) FROM products AS p JOIN order_items AS oi ON oi.product_id = p.id;
SELECT count(*) FROM products AS p LEFT JOIN order_items AS oi ON oi.product_id = p.id;
output, from postgres 18.6
#1 · SELECT 1
countint8
200
(1 row)
#2 · SELECT 1
countint8
24942
(1 row)
#3 · SELECT 1
countint8
24943
(1 row)

and the reason, product by product. the overlap is made of pairs, and the busiest products are in a lot of pairs:

sqldb=shop
SELECT p.id, p.name, count(*) AS rows_in_join
FROM products AS p JOIN order_items AS oi ON oi.product_id = p.id
GROUP BY p.id
ORDER BY rows_in_join DESC, p.id
LIMIT 3;
output, from postgres 18.6
SELECT 3
idint4nametextrows_in_joinint8
1chef's knife1826
2cast iron pan716
3the art of sql559
(3 rows)

and the overlap the circles actually draw, a set operation on product ids:

sqldb=shop
SELECT count(*) FROM (SELECT id FROM products INTERSECT SELECT product_id FROM order_items) AS sold;
SELECT id, name FROM products EXCEPT SELECT p.id, p.name FROM products AS p JOIN order_items AS oi ON oi.product_id = p.id;
output, from postgres 18.6
#1 · SELECT 1
countint8
199
(1 row)
#2 · SELECT 1
idint4nametext
200left-handed teapot
(1 row)

the grid is the meaning, not the method

if postgres really built every pair, this query would make 4,988,400 of them (200 × 24,942) and throw almost all away:

sqldb=shop
SELECT count(*) FROM products CROSS JOIN order_items;
output, from postgres 18.6
SELECT 1
countint8
4988400
(1 row)

it doesn't. the grid tells you what the answer has to be. how to get there is the planner's problem, and for an equi-join it never looks at most of the pairs:

sqldb=shop
EXPLAIN (COSTS OFF)
SELECT p.name, oi.qty
FROM products AS p JOIN order_items AS oi ON oi.product_id = p.id;
output, from postgres 18.6
EXPLAIN
Hash Join Hash Cond: (oi.product_id = p.id) -> Seq Scan on order_items oi -> Hash -> Seq Scan on products p

a Hash Join: put the 200 products in a hash table keyed on id, then stream the order lines past it, one lookup each. that's one of three ways postgres runs a join, and each has a chapter in part 9: nested loop, hash and merge. the answer is the same every time, because it's defined by the grid.

one level deeperthe textbook's version: θ, σ and ×

relational algebra writes a join as a selection over a product: σcondition(A × B). Codd's 1970s papers called the general one a θ-join (θ for any comparison: =, <, <> ...), and the equality-only case an equi-join. the outer joins came later, and the SQL standard spelled them out in SQL-92 as LEFT OUTER JOIN, RIGHT OUTER JOIN and FULL OUTER JOIN (the word OUTER is optional, and nobody types it). relational algebra has the rest of the operators. the important part survives the notation: the product comes first, the filter second, and the padding last.

keylines

  • a join is every pair of rows (the cross product), filtered by ON.
  • ON is a test each pair takes, true keeps it. unknown and false both drop it.
  • an outer join adds back the rows that passed with nobody, padded with NULLs.
  • duplicates multiply: 2 matching rows on each side give 4.
  • venn diagrams draw set operations, not joins.