Sub topic 3
LEFT OUTER JOIN
What this chapter assumes
You should already be able to write a basic SELECT ... FROM ... WHERE query. You should know what primary and foreign keys are, and that NULL means "no value" and not zero or an empty string. You should also have written an INNER JOIN ... ON query. This chapter covers how LEFT JOIN works and the mistakes it invites. Later chapters cover NULL handling, filtering in ON versus WHERE, and aggregation in more depth.
The sample data
The examples use two tables. Cleo has no orders, and order 104 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);An inner join on customer_id returns three rows: Ada twice and Ben once. Cleo is dropped because she has no match, and order 104 is dropped because its customer_id is NULL and equals nothing.
What LEFT JOIN does
A LEFT OUTER JOIN returns every row of the left table, whether or not the ON condition finds a match in the right table. The left table is the one named before the JOIN keyword. It is called the preserved side because none of its rows can disappear. The right table is the unpreserved side, and its rows appear only when they match.
SELECT c.name, o.order_id, o.total
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id;
-- Ada 101 50.00
-- Ada 102 20.00
-- Ben 103 35.00
-- Cleo NULL NULLThe result has four rows. Ada matches two orders and so appears twice. Ben matches one. Cleo matches none, so she appears once, and the columns that would have come from orders are filled with NULL. That filling is called NULL padding.
Order 104 is absent. It lives on the unpreserved side and has no matching customer, so a left join discards it.
The matching algorithm, conceptually
Databases choose their own execution strategy (nested loops, hash joins, merge joins). The logical result is always the same as this procedure:
- Take one row from the left table.
- Find every right-table row for which the
ONcondition is true. - If there are matches, output one combined row per match.
- If there are none, output one row made of the left values plus
NULLfor every right-table column. - Repeat for each left row.
Step 4 is the only difference from an inner join. An inner join stops at "no matches" and outputs nothing for that left row.
Syntax details
LEFT JOIN and LEFT OUTER JOIN mean the same thing. The word OUTER is optional in every major database, and most people omit it.
SELECT c.name, o.order_id
FROM customers c
LEFT OUTER JOIN orders o ON o.customer_id = c.customer_id
ORDER BY c.customer_id, o.order_id;Without ORDER BY, the row order is not guaranteed. The comments in this chapter show a natural order, but your database may return the rows differently.
If both tables use the same column name for the join key, USING is a shorthand supported by PostgreSQL, MySQL and others:
SELECT name, order_id, customer_id
FROM customers
LEFT JOIN orders USING (customer_id);With USING, the join column appears once in the result. For a left join it takes its value from the left table. SQL Server does not support USING, so ON is the portable choice.
The order of the tables matters
Swapping the two tables changes which side is preserved:
SELECT o.order_id, c.name
FROM orders o
LEFT JOIN customers c ON c.customer_id = o.customer_id;
-- 101 Ada
-- 102 Ada
-- 103 Ben
-- 104 NULLNow every order is kept, so order 104 appears with a NULL name. Cleo is gone, because she is on the unpreserved side and has no orders.
A quick way to choose the left table is to complete the sentence "I want every __, with their __ if any." The noun in the first blank goes on the left. "Every customer, with their orders if any" puts customers first.
How many rows to expect
Two rules let you predict a result without running it.
- Lower bound: a left join never returns fewer rows than the left table has. Here
customershas 3 rows, so the result has at least 3. - Growth: each left row produces as many output rows as it has matches, or one row if it has none.
You can check this with counts:
SELECT COUNT(*) AS inner_rows
FROM customers c
JOIN orders o ON o.customer_id = c.customer_id;
-- 3
SELECT COUNT(*) AS left_rows
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id;
-- 4The difference between the two counts is the number of left rows with no match (here, Cleo). It is also the same as the number of left rows that have no match only if each left row has at most one match. With one-to-many data, the left join count includes the extra rows from multiple matches. If you see a left join returning more rows than you expected, a one-to-many relationship is almost always the cause. A later chapter covers that repetition in detail.
Join conditions are not limited to equality
The ON clause accepts any boolean expression, and the preservation rule still applies. You can add extra conditions to it:
SELECT c.name, o.order_id
FROM customers c
LEFT JOIN orders o
ON o.customer_id = c.customer_id
AND o.total >= 30;
-- Ada 101
-- Ben 103
-- Cleo NULLAda's order 102 (total 20.00) does not satisfy the condition, so it is not a match. Ada still appears because order 101 qualifies. A left row with no qualifying match gets the NULL row instead of disappearing. This is the main way ON differs from WHERE, and a later chapter treats it in full.
Common errors
- Choosing the wrong table as the left one. If rows you expected are missing, check which table is preserved. Rows from the right table with no match are always dropped.
- Reading NULL as "no data in the database". A
NULLin a right-table column can mean "no matching row" or "a matching row whose column is itselfNULL". To test for a missing match reliably, check a right-table column that is declaredNOT NULL, such aso.order_id, or the join key. - Expecting a left join to keep right-only rows. Order 104 never appears in the left join from
customers. Only aFULL OUTER JOINwould keep it. - Using
NULLin arithmetic or string concatenation without handling it.o.total * 1.2isNULLfor Cleo. Wrap such expressions inCOALESCE(o.total, 0) * 1.2if you want a number. - Filtering the right table in
WHERE. A condition likeWHERE o.total > 30is false for the NULL-padded row, so Cleo is removed and the query behaves like an inner join. Put such conditions inONwhen you want to keep unmatched left rows. - Testing equality with NULL.
WHERE o.order_id = NULLnever matches anything. UseIS NULL.
Checking your understanding
Use these steps when you write a new left join:
- Name the table whose rows must all appear, and put it in
FROM. - Write the
ONcondition using the key relationship, plus any conditions that limit which right rows count as matches. - Predict the row count: at least the size of the left table, plus extra rows for multiple matches.
- Mark which output columns can be
NULL, and decide how to handle them.
Exercise
Using the sample tables, write a query that returns every customer's name and the orderid of each of their orders, with customers who have no orders still listed. Sort by customerid and then order_id. How many rows come back, and what does Cleo's row look like?
Show answer
SELECT c.name, o.orderid FROM customers c LEFT JOIN orders o ON o.customerid = c.customerid ORDER BY c.customerid, o.orderid; The result has 4 rows: (Ada, 101), (Ada, 102), (Ben, 103) and (Cleo, NULL). Cleo has no matching order, so her orderid column is NULL-padded. Order 104 does not appear because it has no customer and sits on the unpreserved side.
Exercise
You run SELECT o.orderid, c.name FROM orders o LEFT JOIN customers c ON c.customerid = o.customer_id; and want to know how many rows to expect before running it. What is the answer, and why does the result contain a NULL name?
Show answer
The left table is orders, which has 4 rows, and each order matches at most one customer, so the result has exactly 4 rows. Order 104 has a NULL customerid, which equals no customerid, so it is kept as a left row and its name is NULL-padded. Cleo does not appear because customers is the unpreserved side here.