INNER JOIN
matching rows across tables, ON vs USING vs NATURAL, and joining three tables in a row.
- address
- everything.joins.inner_join
- part
- part 3, joins and subqueries
- chapter
- chapter 2 of 11
- reading time
- 8 min
INNER JOIN keeps the pairs of rows where ON is true, and nothing else: a row with no partner just isn't in the result. name the columns with ON, use USING when both sides call the column the same thing, and stay away from NATURAL.
joins chain: each one takes the table built so far and joins one more to it.
the picture
you know how an order in the shop doesn't say who placed it? it says customer_id = 42. the name, the email and the city live in customers, written down once. that's on purpose (the schema design part is about why), and it means almost every useful question needs the tables put back together.
think of a box of receipts that only carry a customer number, and an address book. a join is sitting down with both and writing the name onto every receipt. when the number on the receipt is a foreign key and the address book's is the primary key, every receipt finds exactly one entry, so in that common case a join really does behave like a lookup. in the picture of a join, that's a grid with exactly one tick in every row.
- 1SELECT c.id, c.name
- 2FROM customers AS c
- 3WHERE c.id = 42;
| idint4 | nametext |
|---|---|
| 42 | Ada Lovelace |
customers, narrowed to one row: Ada Lovelace, customer 42.
order_id.notice the row counts: 1, 7, 18, 18. joining a one-to-many table multiplies the rows, joining a many-to-one table doesn't (every line has exactly one product). keep that in mind, it's the whole of the fan-out chapter.
writing one
the smallest useful join: Ada's orders, with her name next to each.
SELECT o.id, o.status, c.name
FROM orders AS o
JOIN customers AS c ON c.id = o.customer_id
WHERE o.customer_id = 42
ORDER BY o.id;| idint4 | statustext | nametext |
|---|---|---|
| 880 | cancelled | Ada Lovelace |
| 1455 | refunded | Ada Lovelace |
| 6580 | delivered | Ada Lovelace |
| 7787 | delivered | Ada Lovelace |
| 8219 | delivered | Ada Lovelace |
| 9615 | delivered | Ada Lovelace |
| 9946 | placed | Ada Lovelace |
the parts:
JOINmeansINNER JOIN. theINNERis optional, and most people leave it off.AS oandAS care table aliases: short names for the rest of the query. once a table has an alias, its real name is gone for that query, so it'so.id, notorders.id.ON c.id = o.customer_idis the test every pair of rows takes. the order of the two sides doesn't matter.
prefix every column with its table, even the ones that only exist on one side. both tables have an id, and postgres won't guess which one you meant:
SELECT id, status
FROM orders JOIN customers ON customers.id = orders.customer_id
WHERE customer_id = 42;who disappears
an inner join keeps pairs. a row that's in no pair is gone, without a warning. the shop has 2,000 customers, and only some of them have ever ordered:
SELECT count(*) AS customers FROM customers;
SELECT count(DISTINCT c.id) AS customers_in_the_join
FROM customers AS c JOIN orders AS o ON o.customer_id = c.id;| customersint8 |
|---|
| 2000 |
| customers_in_the_joinint8 |
|---|
| 1962 |
2,000 customers, 1,962 of them in the join. the other 38 (Ming Li, customer 7, is the first) have no orders, so nothing pairs with them. when "every customer, with their orders if they have any" is the question, you want a LEFT JOIN.
ON, USING and NATURAL
there are three ways to say what to match on. they differ in what you have to type, and in what you get back.
- 1SELECT *
- 2FROM courses AS c
- 3JOIN instructors AS i ON i.id = c.instructor_id
- 4WHERE c.code = 'CS301';
| codetext | titletext | depttext | creditsint2 | instructor_idint4 | idint4 | nametext | depttext | officetext | salarynumeric |
|---|---|---|---|---|---|---|---|---|---|
| CS301 | Databases | CS | 4 | 1 | 1 | Hannah Okoye | CS | B-101 | 98000.00 |
ON names the pair of columns: the course's instructor_id against the instructor's id. one teacher, and every column of both tables, so dept appears twice.
ON, dept appears twice. USING and NATURAL merge it into one column, first. and the last three runs answer a different question from the first.- ON takes any condition. it's the one you'll write most, and the only one that works when the columns are named differently, like
customer_idon one side andidon the other (which is most foreign keys). - USING (col) is shorthand for
ON a.col = b.colwhen both tables have a column with the same name. the output gets that column once instead of twice. handy when a schema names keys the same everywhere (customer_idincustomerstoo). - NATURAL JOIN is
USINGwith every column name the two tables have in common, worked out for you. that's the problem.
SELECT count(*) FROM customers NATURAL JOIN orders;for real:
SELECT count(*) FROM customers NATURAL JOIN orders;| countint8 |
|---|
| 2000 |
in the school it goes the other way. students and instructors share two column names, id and name, so NATURAL JOIN wants a student and an instructor with the same id and the same name:
SELECT count(*) FROM students NATURAL JOIN instructors;| countint8 |
|---|
| 0 |
three tables in a row
a join takes two tables and gives back one. so joins chain: the second JOIN joins a third table to the result of the first, and so on. this is the path from a customer to the names of what they bought, foreign key by foreign key:
hover a stage.
SELECT count(*) FROM customers AS c
JOIN orders AS o ON o.customer_id = c.id;
SELECT count(*) FROM customers AS c
JOIN orders AS o ON o.customer_id = c.id
JOIN order_items AS oi ON oi.order_id = o.id;
SELECT count(*) FROM customers AS c
JOIN orders AS o ON o.customer_id = c.id
JOIN order_items AS oi ON oi.order_id = o.id
JOIN products AS p ON p.id = oi.product_id;| countint8 |
|---|
| 10000 |
| countint8 |
|---|
| 24942 |
| countint8 |
|---|
| 24942 |
and the point of all that joining, the question you'd actually ask: what has Ada bought the most of?
SELECT p.name, sum(oi.qty) AS units
FROM orders AS o
JOIN order_items AS oi ON oi.order_id = o.id
JOIN products AS p ON p.id = oi.product_id
WHERE o.customer_id = 42
GROUP BY p.name
ORDER BY units DESC, p.name
LIMIT 5;| nametext | unitsint8 |
|---|---|
| family soap dish | 5 |
| the art of sql | 5 |
| cast iron pan | 4 |
| classic shower caddy | 4 |
| heavy yo-yo | 4 |
(no customers in that one: the customer id is already on the order, so there's nothing to look up.)
for inner joins, the order you write the tables in doesn't change the answer. a JOIN b JOIN c and c JOIN b JOIN a return the same rows, in some order. so postgres is free to run them in whatever order is cheapest, and picking that order is a search problem of its own. (outer joins are pickier. the next chapter has why.)
one level deeperthe comma join, from before JOIN existed
before SQL-92 added JOIN ... ON, a join was a list of tables in FROM with the condition in WHERE:
EXPLAIN (COSTS OFF)
SELECT o.id, c.name
FROM orders AS o, customers AS c
WHERE c.id = o.customer_id;same Hash Join as the JOIN version. the comma is a CROSS JOIN, and the WHERE filters the product, which is the definition of a join written out longhand. it still works and always will. the risk is that forgetting one condition in a long WHERE silently turns a join into a cross product, while JOIN without an ON is a syntax error. write JOIN ... ON.
keylines
- INNER JOIN keeps the pairs where ON is true. rows with no partner vanish.
- alias your tables and prefix your columns. ambiguous names are an error.
- ON says anything, USING is ON for same-named columns, NATURAL guesses.
- joins chain left to right, and one-to-many joins multiply rows.
- for inner joins, table order and ON vs WHERE don't change the answer.