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).
| customers.city ↓ stores.city → | London soho | Paris marais | Berlin mitte | NULL online |
|---|---|---|---|---|
| London Ada | ✓ | · | · | · |
| London Alan | ✓ | · | · | · |
| Paris Grace | · | ✓ | · | · |
| NULL Edsger | · | · | · | · |
| name | city | stores.city | store |
|---|---|---|---|
| Ada | London | London | soho |
| Alan | London | London | soho |
| Grace | Paris | Paris | marais |
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.
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.
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');CROSS JOIN is the join with no filter at all. every customer, next to every store:
SELECT c.name, c.city, s.city, s.store
FROM customers AS c CROSS JOIN stores AS s
ORDER BY c.name, s.store;| nametext | citytext | citytext | storetext |
|---|---|---|---|
| Ada | London | Paris | marais |
| Ada | London | Berlin | mitte |
| Ada | London | null | online |
| Ada | London | London | soho |
| Alan | London | Paris | marais |
| Alan | London | Berlin | mitte |
| Alan | London | null | online |
| Alan | London | London | soho |
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.
- 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 → | soho | marais | mitte | online |
|---|---|---|---|---|
| Ada | ✓ | · | · | · |
| Alan | ✓ | · | · | · |
| Grace | · | ✓ | · | · |
| Edsger | · | · | · | · |
| nametext | citytext | citytext | storetext |
|---|---|---|---|
| Ada | London | London | soho |
| Alan | London | London | soho |
| Grace | Paris | Paris | marais |
the equi-join: a pair survives when the cities are equal. Edsger's NULL equals nothing, not even the online store's NULL.
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:
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;| nametext | citytext | citytext | storetext |
|---|---|---|---|
| Ada | London | London | soho |
| Alan | London | London | soho |
| Grace | Paris | Paris | marais |
(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:
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;| nametext | citytext | citytext | storetext |
|---|---|---|---|
| Ada | London | London | soho |
| Alan | London | London | soho |
| Edsger | null | null | null |
| Grace | Paris | Paris | marais |
| null | null | Berlin | mitte |
| null | null | null | online |
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.
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:
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;| nametext | storetext |
|---|---|
| Ada | camden |
| Ada | soho |
| Alan | camden |
| Alan | soho |
| Grace | marais |
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.
- 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.
three lies, then:
- 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.
- 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.
- 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:
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;| countint8 |
|---|
| 200 |
| countint8 |
|---|
| 24942 |
| countint8 |
|---|
| 24943 |
and the reason, product by product. the overlap is made of pairs, and the busiest products are in a lot of pairs:
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;| idint4 | nametext | rows_in_joinint8 |
|---|---|---|
| 1 | chef's knife | 1826 |
| 2 | cast iron pan | 716 |
| 3 | the art of sql | 559 |
and the overlap the circles actually draw, a set operation on product ids:
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;| countint8 |
|---|
| 199 |
| idint4 | nametext |
|---|---|
| 200 | left-handed teapot |
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:
SELECT count(*) FROM products CROSS JOIN order_items;| countint8 |
|---|
| 4988400 |
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:
EXPLAIN (COSTS OFF)
SELECT p.name, oi.qty
FROM products AS p JOIN order_items AS oi ON oi.product_id = p.id;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.