Sub topic 4
Reading NULLs in outer join results
This chapter assumes you know basic SELECT, FROM and WHERE, primary and foreign keys, INNER JOIN ... ON, and that NULL means "no value or unknown value" in SQL. It builds on the LEFT JOIN chapter, where unmatched rows first appeared with NULLs. Here you learn to read those NULLs correctly.
Where the NULLs come from
An outer join keeps rows from the preserved side even when the other side has no match. The database still has to return a row with all the columns of the join. For the missing side it fills every column with NULL. This filling is called NULL padding.
The padding is not stored in either table. It exists only in the result set. Because of that, a NULL in a join result can have different causes, and you cannot tell them apart from the value alone.
The examples use the sample tables from this tutorial, plus one nullable column on orders:
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,
coupon VARCHAR(20)
);
INSERT INTO customers (customer_id, name) VALUES
(1, 'Ada'), (2, 'Ben'), (3, 'Cleo');
INSERT INTO orders (order_id, customer_id, total, coupon) VALUES
(101, 1, 50.00, 'SAVE5'),
(102, 1, 20.00, NULL),
(103, 2, 35.00, NULL),
(104, NULL, 15.00, NULL);Two kinds of NULL in one result
Run a LEFT JOIN and select the nullable coupon column:
SELECT c.name, o.order_id, o.coupon
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id;
-- Ada 101 SAVE5
-- Ada 102 NULL
-- Ben 103 NULL
-- Cleo NULL NULLThe coupon column is NULL in three rows, for two different reasons:
| Row | `order_id` | `coupon` | Why `coupon` is NULL |
|---|---|---|---|
| Ada, 102 | 102 | NULL | Stored NULL. The order exists and has no coupon. |
| Ben, 103 | 103 | NULL | Stored NULL. The order exists and has no coupon. |
| Cleo | NULL | NULL | Padding. No order exists at all. |
Looking at coupon alone, you cannot tell Ada's order 102 from Cleo's missing order. Both are NULL, so the column you test must be one that can only be NULL because of padding.
Test a column that is NOT NULL in the right table
A column that is declared NOT NULL can never hold a stored NULL. If it is NULL in a join result, the row must be padding. The primary key of the right table is the usual choice, because primary keys are never NULL.
SELECT c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
WHERE o.order_id IS NULL;
-- CleoUsing o.coupon IS NULL here would return Ada (order 102), Ben and Cleo, which is wrong for "customers with no orders". Using o.customer_id IS NULL would work in this query. It is risky in general, because orders.customer_id is nullable, as order 104 shows.
The join column can lie to you in a different way
Padding applies to every column of the unpreserved table, including the join column itself. Reverse the direction so orders is preserved:
SELECT o.order_id, o.customer_id AS order_customer_id,
c.customer_id AS customer_customer_id, c.name
FROM orders o
LEFT JOIN customers c ON c.customer_id = o.customer_id;
-- 101 1 1 Ada
-- 102 1 1 Ada
-- 103 2 2 Ben
-- 104 NULL NULL NULLFor order 104, o.customer_id is NULL because that value is stored in the table. The columns from c are NULL because of padding. When a query selects the join key, always check which table's copy you are reading. In a LEFT JOIN, c.customer_id is NULL for unmatched rows, while the copy from the preserved table keeps its real value. This matters most with FULL OUTER JOIN, where either copy can be padded.
Why NULL padding does not match anything
NULL is not equal to anything, including NULL. A comparison with NULL gives UNKNOWN, and WHERE keeps only rows where the condition is TRUE. Two consequences follow for outer join results:
WHERE o.order_id = NULLreturns no rows. UseIS NULLorIS NOT NULL.- Any ordinary comparison on a padded column removes the padded rows.
WHERE o.total <> 50drops Cleo, becauseNULL <> 50is UNKNOWN, not TRUE.
The second point is the main reason a LEFT JOIN silently behaves like an inner join. A later chapter covers it in full under filtering in ON versus WHERE. For now, remember that every condition on an unpreserved column in WHERE has to decide what to do with padded rows.
If you want to keep the unmatched rows and also filter, state it explicitly:
SELECT c.name, o.order_id, o.total
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
WHERE o.order_id IS NULL OR o.total > 30;
-- Ada 101 50.00
-- Ben 103 35.00
-- Cleo NULL NULLReplacing NULLs for display with COALESCE
COALESCE(a, b, ...) returns the first argument that is not NULL. It is the standard way to show a readable value instead of padding:
SELECT c.name,
COALESCE(CAST(o.order_id AS VARCHAR(10)), 'no orders') AS order_ref,
COALESCE(o.total, 0) AS 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 no orders 0The cast is needed because COALESCE requires its arguments to have compatible types, and a number and a string do not. Some databases are lenient about this, but the cast works everywhere.
COALESCE also has a limit. It destroys the distinction between padding and stored values. With COALESCE(o.coupon, 'none'), Cleo's missing order and Ada's order without a coupon both show none. Apply COALESCE only at the last step, for display, and never in a condition you use to find unmatched rows.
Labeling matched and unmatched rows with CASE
When you need the difference to survive in the output, test the NOT NULL column and label the row:
SELECT c.name,
CASE WHEN o.order_id IS NULL THEN 'no orders' ELSE 'has orders' END AS status,
o.coupon
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id;
-- Ada has orders SAVE5
-- Ada has orders NULL
-- Ben has orders NULL
-- Cleo no orders NULLThe status column is reliable even where coupon is not.
A decision path for any NULL
Common errors
- Testing the wrong column. Using a nullable column for the "no match" test returns rows that do have a match.
- Using
= NULL. It never matches. UseIS NULL. - Filtering the unpreserved table in
WHERE. Padded rows fail the comparison and disappear, which undoes the outer join. - Applying COALESCE too early. If you replace NULLs in a subquery or in a join condition, you cannot detect unmatched rows later.
- Assuming row order. The sample outputs are shown in a convenient order. Without
ORDER BY, the database may return the rows in any order.
Exercise
Using the sample tables, you want a list of orders that have no customer. Which query is correct, and why would WHERE c.name IS NULL be less safe if customers.name were nullable?
SELECT o.orderid
FROM orders o
LEFT JOIN customers c ON c.customerid = o.customer_id
WHERE ...
Show answer
Use WHERE c.customer_id IS NULL. It returns order 104. customer_id is the primary key of customers, so it can only be NULL through padding. If name were nullable, a customer with a stored NULL name would match an order and be wrongly reported as missing. The same is true of testing o.customer_id IS NULL, which finds orders whose foreign key is NULL but does not detect a foreign key that points to a missing customer.
Exercise
A LEFT JOIN from customers to orders returns three rows where coupon is NULL for Ada, Ben and Cleo. Write the expression that tells apart Cleo from the other two, and say what it returns for each.
Show answer
CASE WHEN o.order_id IS NULL THEN 'no orders' ELSE 'has orders' END. It returns has orders for Ada (order 102) and Ben (order 103), and no orders for Cleo, because order_id is NOT NULL in orders and is NULL only in the padded row.