11. JOIN: reading several tables at once

Put tables linked by their id numbers together for one answer: orders with the customer's name, lines with the product's name.

Why the data is split into tables

Look at product again. A product doesn't keep its category's name, only the number category_id:

SELECT id, name, category_id FROM product WHERE id <= 4;
idnamecategory_id
1Coffee1
2Green Tea1
3Orange Juice1
4Croissant2
4 rows

Why not just write Drinks there? Because the day the shop renames Drinks to Beverages, every product in it would have to be changed, and miss one and the data contradicts itself. With the name kept in one place, the category table, one row changes and that's it. Orders are the same: they keep only customer_id, not the customer's name, city and phone again on every order.

Splitting keeps the data right and free of repeats. But when we read, we want names, not numbers, so the tables have to be joined back together: JOIN.

INNER JOIN ... ON

Put the first table after FROM, the second after JOIN, and say after ON when a row of one goes with a row of the other:

SELECT product.name, category.name
FROM product
JOIN category ON product.category_id = category.id
ORDER BY product.id;
namename
CoffeeDrinks
Green TeaDrinks
Orange JuiceDrinks
CroissantBakery
Banana BreadBakery
CheesecakeBakery
Potato ChipsSnacks
Dried MangoSnacks
Cashew NutsSnacks
NotebookStationery
PenStationery
HighlighterStationery
12 rows

The database pairs every product with the category whose id matches its category_id: 12 rows, one per product.

Both tables have a column called name, so table.column says which one is meant. The result also has two columns headed name; give them names of their own with AS (as in the next example).

JOIN alone and INNER JOIN are the same thing. Inner means only rows that found a partner: a row with none is left out of the result (chapter 12 is about those).

Short names for tables

Long table names written again and again get tiring. Give a table a short name (an alias) after its name, with or without AS:

SELECT o.id, o.ordered, c.name AS customer, o.status
FROM orders AS o
JOIN customer AS c ON c.id = o.customer_id
ORDER BY o.id;
idorderedcustomerstatus
12026-09-02Somchai Jaideepaid
22026-09-05Malee Srisukshipped
32026-09-12Somchai Jaideeshipped
42026-09-20Anan Wongsapaid
52026-10-01Pim Chaiyacancelled
62026-10-03Narin Thongdeeshipped
72026-10-10Malee Srisukpaid
82026-10-15Kanya Boonmeeshipped
92026-10-22Wichai Saelimpaid
102026-10-28Somchai Jaideepaid
112026-11-02Siriporn Kaewdeeshipped
122026-11-05Pim Chaiyapaid
132026-11-11Kanya Boonmeepaid
142026-11-18Anan Wongsacancelled
152026-11-25Wichai Saelimpaid
15 rows

All 15 orders with the customer's name. o is orders and c is customer; once given, the short name is used all through the statement.

JOIN works with everything so far: WHERE, ORDER BY, GROUP BY. The orders of Bangkok customers that haven't been shipped yet:

SELECT o.id, c.name, c.city, o.status
FROM orders o
JOIN customer c ON c.id = o.customer_id
WHERE c.city = 'Bangkok' AND o.status = 'paid'
ORDER BY o.id;
idnamecitystatus
1Somchai JaideeBangkokpaid
4Anan WongsaBangkokpaid
9Wichai SaelimBangkokpaid
10Somchai JaideeBangkokpaid
15Wichai SaelimBangkokpaid
5 rows

5 orders, from 3 Bangkok customers. WHERE can use a column of any table joined in.

An order's lines: product names and line totals

order_item holds only numbers. Join it to product for the product's name, and work out each line's total:

SELECT i.order_id, p.name AS product, i.qty, i.price, i.qty * i.price AS line_total
FROM order_item i
JOIN product p ON p.id = i.product_id
WHERE i.order_id = 9
ORDER BY p.name;
order_idproductqtypriceline_total
9Cheesecake2120.0240.0
9Coffee255.0110.0
9Croissant435.0140.0
3 rows

Order 9 has 3 lines, adding up to 490 baht, as chapter 9 found.

order_item keeps its own price (i.price): the price when it sold. p.price is the price today. When the shop raises a price one day, old orders are still right; so sales are always worked out from i.price.

Three tables and more

JOINs follow one another, each with its own ON. Every order line with its date, customer, product and category joins five tables:

SELECT o.id AS order_id, o.ordered, c.name AS customer, p.name AS product, cat.name AS category, i.qty
FROM order_item i
JOIN orders   o   ON o.id   = i.order_id
JOIN customer c   ON c.id   = o.customer_id
JOIN product  p   ON p.id   = i.product_id
JOIN category cat ON cat.id = p.category_id
ORDER BY o.id, p.name;
order_idorderedcustomerproductcategoryqty
12026-09-02Somchai JaideeCoffeeDrinks2
12026-09-02Somchai JaideeCroissantBakery2
22026-09-05Malee SrisukDried MangoSnacks1
22026-09-05Malee SrisukPotato ChipsSnacks3
32026-09-12Somchai JaideeCheesecakeBakery1
32026-09-12Somchai JaideeCoffeeDrinks1
42026-09-20Anan WongsaNotebookStationery5
42026-09-20Anan WongsaPenStationery10
52026-10-01Pim ChaiyaCashew NutsSnacks1
62026-10-03Narin ThongdeeBanana BreadBakery1
62026-10-03Narin ThongdeeGreen TeaDrinks4
62026-10-03Narin ThongdeePotato ChipsSnacks2
72026-10-10Malee SrisukCoffeeDrinks1
72026-10-10Malee SrisukDried MangoSnacks2
82026-10-15Kanya BoonmeeNotebookStationery3
82026-10-15Kanya BoonmeePenStationery20
92026-10-22Wichai SaelimCheesecakeBakery2
92026-10-22Wichai SaelimCoffeeDrinks2
92026-10-22Wichai SaelimCroissantBakery4
102026-10-28Somchai JaideeGreen TeaDrinks1
28 rows (the first 20 shown)

28 rows, as many as order_item has: every line finds exactly one order, customer, product and category.

Read a long JOIN as a path: from the line (order_item) to its order (orders), from the order to its customer (customer), and from the line to its product (product) and on to its category (category).

A join can be grouped, too. What each customer spent, cancelled orders left out:

SELECT c.name AS customer, count(DISTINCT o.id) AS orders, sum(i.qty * i.price) AS spent
FROM customer c
JOIN orders o     ON o.customer_id = c.id
JOIN order_item i ON i.order_id = o.id
WHERE o.status <> 'cancelled'
GROUP BY c.id, c.name
ORDER BY spent DESC, c.name;
customerordersspent
Wichai Saelim2865.0
Kanya Boonmee2480.0
Malee Srisuk2400.0
Somchai Jaidee3400.0
Anan Wongsa1300.0
Siriporn Kaewdee1300.0
Narin Thongdee1290.0
Pim Chaiya1175.0
8 rows

Wichai Saelim spent the most, 865 baht. There are 8 customers in the result: the 2 who never ordered are missing, because the JOIN found no order to pair them with. Chapter 12 brings them back.

count(DISTINCT o.id) matters here: joined to order_item, one order becomes several rows (one per line), and count(*) would count lines, not orders.

USING when the names match

When the matching columns have the same name in both tables, USING (name) can stand in for ON. Our shop names them differently (orders.id and order_item.order_id), so it doesn't fit there. Make a small promotion table with a product_id column, like order_item's (making tables is in chapters 16 and 20; just run it for now):

CREATE TABLE promo (product_id INTEGER, discount INTEGER);
INSERT INTO promo VALUES (1, 10), (7, 5), (11, 2);
✓ 3 rows changed
SELECT order_id, product_id, qty, discount
FROM order_item
JOIN promo USING (product_id)
ORDER BY order_id, product_id;
order_idproduct_idqtydiscount
11210
2735
31110
411102
6725
71110
811202
91210
11765
121110
151152
11 rows

11 lines: every line that sold product 1, 7 or 11, the ones on promotion.

USING (product_id) is ON order_item.product_id = promo.product_id, and product_id can be written alone, with no table, since both tables have the same value there.

Error: ambiguous column name

Write a column that both tables have, without saying whose, and the database can't choose:

SELECT id, name FROM product p JOIN category c ON p.category_id = c.id;
Error: ambiguous column name: id

Ambiguous means it could be either: id is in product and in category. The fix is the table's name (or short name) before every column whose name is shared:

SELECT p.id, p.name, c.name AS category FROM product p JOIN category c ON p.category_id = c.id ORDER BY p.id;
idnamecategory
1CoffeeDrinks
2Green TeaDrinks
3Orange JuiceDrinks
4CroissantBakery
5Banana BreadBakery
6CheesecakeBakery
7Potato ChipsSnacks
8Dried MangoSnacks
9Cashew NutsSnacks
10NotebookStationery
11PenStationery
12HighlighterStationery
12 rows

In a statement with a JOIN, put the short name before every column, even one whose name isn't shared. The reader sees at once which table each comes from, and the day someone adds a column of the same name to the other table, the statement doesn't break.

Don't forget ON. SQLite lets you write JOIN without it, and then pairs every row with every row: 12 products and 4 categories make 48 rows, though each product is in only one category. When a result has far more rows than you expected, check the ON first.

SELECT count(*) FROM product JOIN category;
count(*)
48
1 row
  1. Show the name, price and category name of the products over 50 baht, by price.
  2. Show every line of order 6: the product's name, the quantity and the line total.
  3. Which orders did customers from Chiang Mai place? Show the order number, the date and the customer's name.
  4. Sales per category (by name), shipped orders (shipped) only.
Show the answer
SELECT p.name, p.price, c.name AS category FROM product p JOIN category c ON c.id = p.category_id WHERE p.price > 50 ORDER BY p.price;
SELECT p.name, i.qty, i.qty * i.price AS line_total FROM order_item i JOIN product p ON p.id = i.product_id WHERE i.order_id = 6 ORDER BY p.name;
SELECT o.id, o.ordered, c.name FROM orders o JOIN customer c ON c.id = o.customer_id WHERE c.city = 'Chiang Mai' ORDER BY o.id;
SELECT cat.name, sum(i.qty * i.price) AS sales FROM order_item i JOIN orders o ON o.id = i.order_id JOIN product p ON p.id = i.product_id JOIN category cat ON cat.id = p.category_id WHERE o.status = 'shipped' GROUP BY cat.name ORDER BY sales DESC;
namepricecategory
Coffee55.0Drinks
Banana Bread60.0Bakery
Dried Mango90.0Snacks
Cheesecake120.0Bakery
Cashew Nuts150.0Snacks
5 rows
nameqtyline_total
Banana Bread160.0
Green Tea4180.0
Potato Chips250.0
3 rows
idorderedname
22026-09-05Malee Srisuk
72026-10-10Malee Srisuk
82026-10-15Kanya Boonmee
132026-11-11Kanya Boonmee
4 rows
namesales
Snacks515.0
Stationery390.0
Drinks235.0
Bakery180.0
4 rows

Phai (bamboo), given as a gift of knowledge: free to use, learn from and pass on · every example on this page was run on Phai SQL and checked against SQLite when the page was made