Sub topic 11
Combining Tables with Joins
Assume you know how tables, primary keys, and foreign keys work. A join is a SQL operation that combines rows from two or more tables by matching related column values.
A relational database keeps related facts in separate tables. For example, a customers table stores customer details, while an orders table stores purchases. The orders.customer_id foreign key points to customers.customer_id.
Inner joins
An inner join returns only rows that have a match in both tables. The ON clause states how the tables relate.
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL REFERENCES customers (customer_id),
total_amount DECIMAL(10, 2) NOT NULL
);
INSERT INTO customers (customer_id, name)
VALUES
(1, 'Ada Lovelace'),
(2, 'Grace Hopper');
INSERT INTO orders (order_id, customer_id, total_amount)
VALUES
(100, 1, 59.90),
(101, 1, 24.50);
SELECT c.name, o.order_id, o.total_amount
FROM customers AS c
JOIN orders AS o
ON o.customer_id = c.customer_id
ORDER BY o.order_id;The aliases c and o are short names for the tables. The result contains Ada’s two orders. Grace does not appear because she has no matching order.
A join can return several result rows for one row in the first table. This is expected in a one-to-many relationship. One customer can have many orders, so the customer’s details are repeated once for each matching order.
Left joins
A left join keeps every row from the table written after FROM, even when no matching row exists. Missing values from the other table appear as NULL.
SELECT c.name, o.order_id, o.total_amount
FROM customers AS c
LEFT JOIN orders AS o
ON o.customer_id = c.customer_id
ORDER BY c.customer_id, o.order_id;This query includes Grace with NULL values for the order columns. Use a left join when unmatched rows matter, such as finding customers who have not placed an order.
Common join errors
- Join on the related key columns, not on names that merely look similar.
- Check whether the relationship is one-to-many. A join can multiply rows.
- Select columns with table aliases when both tables have a column with the same name.
- Use
COUNT,SUM, orDISTINCTonly when their effect on duplicates is clear. - An inner join hides unmatched rows. Use a left join when you need to detect missing relationships.
For example, this query finds customers without orders:
SELECT c.customer_id, c.name
FROM customers AS c
LEFT JOIN orders AS o
ON o.customer_id = c.customer_id
WHERE o.order_id IS NULL;The IS NULL test is required. SQL uses NULL to represent an unknown or missing value, so o.order_id = NULL does not work.
Exercise
Which join should you use to list every customer, including customers who have never placed an order?
Show answer
Use a LEFT JOIN from customers to orders, then test the order columns for NULL when you need only customers without orders.