Sub topic 1
SQL Inner Joins: How Tables Relate
Prerequisites
This chapter assumes you can write basic SELECT, FROM, WHERE and ORDER BY queries. You should know what a table, row and column are, and understand primary keys and foreign keys. You should also be able to run SQL against a relational database.
How tables relate
A primary key is a column that uniquely identifies each row in a table. A foreign key is a column that stores a primary key value from another table. Foreign keys record how rows in different tables belong together.
The sample schema below has two tables. orders.customer_id is a foreign key that points 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);From every combination to matching rows
If you list two tables in FROM with no join condition, the database pairs every row of one table with every row of the other. This is a Cartesian product. Three customers and four orders produce 3 × 4 = 12 rows.
SELECT c.name, o.id AS order_id
FROM customers AS c, orders AS o;An inner join keeps only the pairs whose join columns match. Most of the 12 pairs are wrong, such as Ada paired with order 103. The join removes them.
Writing your first INNER JOIN
An INNER JOIN combines two tables. The ON clause states the matching rule.
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;This query returns three rows: Ada with order 101, Ada with order 102, and Ben with order 103.
Table aliases and qualified column names
An alias is a short name for a table, written as customers AS c. A qualified column name puts the alias in front of the column, such as c.name.
Qualification is required when both tables have a column with the same name. Both tables here have an id column, so c.id and o.id refer to different things. Without the prefix, the database raises an "ambiguous column" error.
Join conditions in the ON clause
The ON clause decides which row pairs enter the result. Equality, as in o.customer_id = c.id, is the most common form. The condition can be any expression that is true for matching rows. Keep the rule in ON so the reader sees how the tables connect.
Exercise:
Exercise
How many rows does the INNER JOIN query in "Writing your first INNER JOIN" return, and why does Chloe not appear?
Show answer
It returns three rows: Ada's orders 101 and 102, and Ben's order 103. Chloe has no order whose customer_id matches her id, so the join produces no pair for her.