The orders table from the last lesson only stores a customer number. That is tidy for the database, but hard to read: you want to see "Budi bought a Laptop", not "1 bought a Laptop". Budi's name is in the customers table, while the product is in the orders table. So something has to join the two.
That's the job of a JOIN: it combines rows from two tables into one result by pairing the rows whose values match. An INNER JOIN keeps only the pairs that are found. Imagine clipping every order receipt to the member card with the same number. A receipt with no member number can't be clipped to any card, and a member who has never shopped has no receipt. Neither goes into the result pile. Here, a member card is a row in customers, and a receipt is a row in orders.
The data
The same tables as in the Table Relationships lesson. orders.customer_id points at customers.id.
customers
| id | name |
|---|---|
| 1 | Budi |
| 2 | Siti |
| 3 | Andi |
orders
| id | customer_id | product |
|---|---|---|
| 1 | 1 | Laptop |
| 2 | 1 | Mouse |
| 3 | 2 | Monitor |
| 4 | NULL | Webcam |
Writing an INNER JOIN
This query pairs every customer with their orders:
SELECT customers.name AS customer_name, orders.product AS product_name
FROM customers
INNER JOIN orders ON customers.id = orders.customer_id;
FROM customers: the first table, called the left table.INNER JOIN orders: the second table, the one being joined, called the right table.ON customers.id = orders.customer_id: the pairing rule. A customer and an order are paired when the customer'sidequals the order'scustomer_id. These two columns are the primary key and the foreign key from the previous lesson.customers.name: table name, dot, then column name. Once a query uses two tables, write the table name so it's clear which table the column belongs to.AS customer_name: an alias, the column's new heading in the query result. WithoutAS, the heading isname.JOINon its own (noINNER) means exactly the same as INNER JOIN.
Step by step
Before you look at the steps, guess: from 3 customers and 4 orders, how many rows does this INNER JOIN give? 3, 4 or 12?
Picture the database trying every pair of customer and order (3 × 4 = 12 pairs), then keeping the pairs whose ON rule is true. A real database finds them in a faster way, but the result is the same. This table shows the pairs that match, and the rows that have no partner:
| Customer | Order (customer_id) | customers.id = orders.customer_id |
Kept? |
|---|---|---|---|
| 1 Budi | Laptop (1) | 1 = 1, true | yes |
| 1 Budi | Mouse (1) | 1 = 1, true | yes |
| 2 Siti | Monitor (2) | 2 = 2, true | yes |
| 3 Andi | no order has customer_id 3 | no | |
| anyone | Webcam (NULL) | 1 = NULL is not true | no |
The result:
| customer_name | product_name |
|---|---|
| Budi | Laptop |
| Budi | Mouse |
| Siti | Monitor |
3 rows, not 12. Budi appears twice because he has two orders. Andi isn't in the result because he has no orders. The Webcam isn't either, because its customer_id is NULL (empty, no value yet), and no comparison with NULL is ever true.
Table aliases
Writing customers. and orders. over and over makes a query long. Give each table a short name, called a table alias:
SELECT c.name AS customer_name, o.product AS product_name
FROM customers c
INNER JOIN orders o ON c.id = o.customer_id;
customers c: in this query, thecustomerstable is calledc, andordersis calledo.- Once a table has an alias, use the alias. If this query used
customers.name, SQLite would answerno such column: customers.name.
When the ON is wrong
You can try all of these against real SQLite in the Lab:
- The wrong column:
ON c.id = o.idpairs customer numbers with order numbers. The result is still 3 rows with no error, but Siti gets the Mouse and Andi gets the Monitor. A query that runs isn't necessarily right. - No ON:
FROM customers c INNER JOIN orders ois accepted by SQLite (and MySQL) as "pair everything": 3 × 4 = 12 rows. PostgreSQL rejects it with a syntax error. - A typo:
ON c.id = o.customeris answered withno such column: o.customer.
📌 Joining three tables
JOINs can be chained. Suppose there is a reviews table with an order_id column (the number of the order being reviewed). Each order's review can be included too:
SELECT c.name, o.product, r.rating
FROM customers c
INNER JOIN orders o ON c.id = o.customer_id
INNER JOIN reviews r ON o.id = r.order_id;
Each INNER JOIN has its own ON, and each JOIN can drop rows that have no partner.
⚠️ Rows that multiply, columns that clash
- Forgetting
ONor using the wrong column. The number of rows grows (to 12 rows) or the pairs are wrong, often with no error. Pair the primary key with its foreign key:c.id = o.customer_id. - A column that exists in both tables, without a table name.
SELECT id, name, product ...is answered withambiguous column name: id. This means SQLite doesn't know whichidyou mean, becausecustomersandordersboth have anid. Writec.idoro.id. - Forgetting
AS. In the exercise, the checker looks for columns namedcustomer_nameandproduct_name. Without aliases they are callednameandproduct. - Expecting rows with no partner to appear. Andi and the Webcam never appear in an INNER JOIN. To keep them, use a LEFT or RIGHT JOIN (the next lesson).
TL;DR: A JOIN combines rows from two tables by pairing the rows whose values match. SELECT ... FROM customers INNER JOIN orders ON customers.id = orders.customer_id pairs every customer with their orders. ON is the pairing rule, and an INNER JOIN keeps only the pairs whose ON is true. In this example, 3 customers and 4 orders become 3 rows: Budi twice, Siti once. Andi (no orders) and the Webcam (a guest order, customer_id NULL) are not in the result. Use AS to give result columns a new heading, table aliases (customers c) to shorten table names, and a table name in front of any column that exists in both tables. An ON on the wrong column gives wrong results with no error, and a missing ON pairs everything (12 rows).
⚡ Pair up two tables
Write:
SELECT customers.name AS customer_name, orders.product AS product_name
FROM customers
INNER JOIN orders ON customers.id = orders.customer_id;
Meaning: INNER JOIN combines the customers and orders tables by pairing their rows. ON is the pairing rule: the customer's id equals the order's customer_id, the foreign key that points at the customer. Put the table name in front of each column, like customers.name, because there are two tables now. AS gives a result column a new heading.
In the exercise, the checker looks for the columns customer_name and product_name, so don't forget AS.
⚡ How many rows?
Guess first: the customers are Budi, Siti and Andi. Budi has 2 orders, Siti 1, Andi has never ordered, and the fourth order (the Webcam) has a NULL customer_id. How many rows does the INNER JOIN give?
Three. Budi twice, Siti once. Andi has no orders, and the Webcam's customer_id is NULL, so neither has a partner.
Meaning: An INNER JOIN only keeps the pairs whose ON rule is true.
⚡ Table aliases
Write:
SELECT c.name AS customer_name, o.product AS product_name
FROM customers c
INNER JOIN orders o ON c.id = o.customer_id;
Meaning: customers c gives the customers table the short name c, and orders o gives orders the short name o. This short name is called a table alias. Once a table has an alias, use the alias: c.name, not customers.name.
⚡ A wrong ON
Meaning: ON c.id = o.id pairs customer numbers with order numbers. The query still runs with no error, but the pairs are wrong. With no ON, SQLite pairs every customer with every order: 3 × 4 = 12 rows. A query that runs isn't necessarily right.