Sub topic 1
Starting point: what an inner join drops
Prerequisites
This chapter assumes you can write SELECT, FROM and WHERE clauses, that you understand primary and foreign keys, that you know how NULL behaves in SQL, and that you have written an INNER JOIN with an ON condition.
The sample data
The examples use two small tables. customers has three rows. orders has four rows, and one order has no customer.
CREATE TABLE customers (
customer_id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL
);
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT REFERENCES customers (customer_id),
total DECIMAL(10, 2) NOT NULL
);
INSERT INTO customers (customer_id, name) VALUES
(1, 'Ada'), (2, 'Ben'), (3, 'Cleo');
INSERT INTO orders (order_id, customer_id, total) VALUES
(101, 1, 50.00), (102, 1, 20.00), (103, 2, 35.00), (104, NULL, 15.00);What an inner join drops
An inner join returns only the row pairs where the ON condition is true. A row with no match on the other side disappears from the result.
SELECT c.name, o.order_id, o.total
FROM customers c
INNER JOIN orders o ON o.customer_id = c.customer_id;The result has three rows: Ada with order 101, Ada with order 102, and Ben with order 103. Cleo is missing because she has no orders. Order 104 is missing because its customer_id is NULL, and NULL never equals anything, including another NULL.
The idea behind outer joins: preserving rows
An outer join keeps rows from one table, the preserved side, even when no match exists. A LEFT OUTER JOIN preserves every row of the left table. Unmatched rows get NULL in the columns that come from the other table.
LEFT OUTER JOIN
LEFT JOIN is shorthand for LEFT OUTER JOIN. The keyword OUTER is optional.
SELECT c.name, o.order_id, o.total
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id;The result has four rows. Cleo now appears with NULL in order_id and total. Order 104 still does not appear, because a LEFT JOIN preserves customers, not orders.
Reading NULLs in outer join results
A NULL from the right table means "no matching row." It does not mean zero or an empty string. Test for it with IS NULL, because = NULL never returns true.
SELECT c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
WHERE o.order_id IS NULL;This query returns Cleo. To show a default value instead of NULL, wrap the column in COALESCE:
SELECT c.name, COALESCE(o.total, 0) AS total
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id;Exercise
Using the sample tables, how many rows does SELECT c.name FROM customers c LEFT JOIN orders o ON o.customer_id = c.customer_id return, and why?
Show answer
It returns 4 rows. Ada appears twice, once for each of her orders, Ben appears once, and Cleo appears once with NULL order columns because a LEFT JOIN keeps unmatched left-side rows.