Sub topic 3
Writing Your First `INNER JOIN`
Assume you know basic SELECT, FROM, WHERE, and ORDER BY syntax. You should also understand that a primary key identifies a row and a foreign key stores a related row's key.
An inner join combines rows from two tables when a condition matches. Rows without a match are excluded from the result.
The sample tables
The customers table has one row per customer. The orders table has one row per order. orders.customer_id refers to customers.id.
CREATE TABLE customers (
id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
CREATE TABLE orders (
id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (id),
order_date DATE NOT NULL,
total DECIMAL(10, 2) NOT NULL
);
INSERT INTO customers (id, name) VALUES
(1, 'Ada'),
(2, 'Ben'),
(3, 'Chloe');
INSERT INTO orders (id, customer_id, order_date, total) VALUES
(101, 1, '2026-01-05', 50.00),
(102, 1, '2026-02-10', 75.00),
(103, 2, '2026-02-11', 20.00),
(104, NULL, '2026-03-01', 99.00);Chloe has no order. Order 104 has no customer because its customer_id is NULL.
The basic syntax
Write the table containing the first set of rows after FROM. Then add INNER JOIN, the second table, and an ON condition.
SELECT c.name, o.id AS order_id, o.total
FROM customers AS c
INNER JOIN orders AS o
ON o.customer_id = c.id;The aliases c and o are short names for the two tables. The qualified column names, such as c.id, identify exactly which table supplies each column.
The ON condition says that an order matches a customer when orders.customer_id equals customers.id. The query returns:
| name | order_id | total |
|---|---|---|
| Ada | 101 | 50.00 |
| Ada | 102 | 75.00 |
| Ben | 103 | 20.00 |
Ada appears twice because she has two matching orders. Chloe is absent because no order matches her ID. Order 104 is absent because NULL = any value is not true, so it cannot satisfy the join condition.
Joining and filtering
An inner join establishes which rows belong together. A WHERE clause then filters the joined rows.
SELECT c.name, o.id AS order_id, o.order_date
FROM customers AS c
INNER JOIN orders AS o
ON o.customer_id = c.id
WHERE o.total > 30
ORDER BY o.order_date;This query first finds the three matching customer-order rows. The WHERE clause keeps only orders whose total is greater than 30, so it returns Ada's orders 101 and 102.
Exercise
Which rows appear for this query: SELECT c.name, o.id FROM customers AS c INNER JOIN orders AS o ON o.customer_id = c.id WHERE c.name = 'Ben';?
Show answer
One row appears: Ben with order 103.