skip to content

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.

query.sql
  1. 1SELECT c.id, c.name
  2. 2FROM customers AS c
  3. 3WHERE c.id = 42;
idint4nametext
42Ada Lovelace
(1 row)

customers, narrowed to one row: Ada Lovelace, customer 42.

query 1/4
real output, postgres 18.6 (PGlite 0.5.12) · inner-chain
step through it. Ada is one row, then one row per order (her name repeats), then one row per order line, then the product names. shaded bands are the rows that share an 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.

sqldb=shop
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;
output, from postgres 18.6
SELECT 7
idint4statustextnametext
880cancelledAda Lovelace
1455refundedAda Lovelace
6580deliveredAda Lovelace
7787deliveredAda Lovelace
8219deliveredAda Lovelace
9615deliveredAda Lovelace
9946placedAda Lovelace
(7 rows)

the parts:

  • JOIN means INNER JOIN. the INNER is optional, and most people leave it off.
  • AS o and AS c are 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's o.id, not orders.id.
  • ON c.id = o.customer_id is 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:

sqldb=shop
SELECT id, status
FROM orders JOIN customers ON customers.id = orders.customer_id
WHERE customer_id = 42;
output, from postgres 18.6
ERROR 42702: column reference "id" is ambiguous
1 │ SELECT id, status
at line 1, column 8

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:

sqldb=shop
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;
output, from postgres 18.6
#1 · SELECT 1
customersint8
2000
(1 row)
#2 · SELECT 1
customers_in_the_joinint8
1962
(1 row)

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.

spelling =
query.sql
  1. 1SELECT *
  2. 2FROM courses AS c
  3. 3JOIN instructors AS i ON i.id = c.instructor_id
  4. 4WHERE c.code = 'CS301';
the result for ON the instructor
codetexttitletextdepttextcreditsint2instructor_idint4idint4nametextdepttextofficetextsalarynumeric
CS301DatabasesCS411Hannah OkoyeCSB-10198000.00
(1 row)

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.

real output, postgres 18.6 (PGlite 0.5.12) · inner-spelling
switch the spelling. watch the columns: with 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_id on one side and id on the other (which is most foreign keys).
  • USING (col) is shorthand for ON a.col = b.col when 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_id in customers too).
  • NATURAL JOIN is USING with every column name the two tables have in common, worked out for you. that's the problem.
predict the output
sql
SELECT count(*) FROM customers NATURAL JOIN orders;

for real:

sqldb=shop
SELECT count(*) FROM customers NATURAL JOIN orders;
output, from postgres 18.6
SELECT 1
countint8
2000
(1 row)

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:

sqldb=school
SELECT count(*) FROM students NATURAL JOIN instructors;
output, from postgres 18.6
SELECT 1
countint8
0
(1 row)

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.

hover a stage. each join takes the table built so far and adds one more. the counts are the whole shop, from the block below.
sqldb=shop
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;
output, from postgres 18.6
#1 · SELECT 1
countint8
10000
(1 row)
#2 · SELECT 1
countint8
24942
(1 row)
#3 · SELECT 1
countint8
24942
(1 row)

and the point of all that joining, the question you'd actually ask: what has Ada bought the most of?

sqldb=shop
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;
output, from postgres 18.6
SELECT 5
nametextunitsint8
family soap dish5
the art of sql5
cast iron pan4
classic shower caddy4
heavy yo-yo4
(5 rows)

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

sqldb=shop
EXPLAIN (COSTS OFF)
SELECT o.id, c.name
FROM orders AS o, customers AS c
WHERE c.id = o.customer_id;
output, from postgres 18.6
EXPLAIN
Hash Join Hash Cond: (o.customer_id = c.id) -> Seq Scan on orders o -> Hash -> Seq Scan on customers c

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.