Sub topic 7
Filtering in ON versus WHERE
This chapter assumes you can write basic SELECT queries with WHERE, you know how NULL behaves in comparisons, and you have written an INNER JOIN ... ON. It uses the customers and orders tables from the earlier chapters. Ada has orders 101 and 102, Ben has order 103, Cleo has no orders, and order 104 has no customer.
With an inner join, a condition in ON and the same condition in WHERE give the same rows. With an outer join they do not. Moving a condition from one clause to the other can change which rows the query returns, including the preserved rows that make it an outer join. This chapter explains why and gives a rule for choosing.
Two different jobs
ON and WHERE run at different stages and do different things.
ONdecides which right-side rows match each left-side row. It defines the match.WHEREruns after the join is finished and removes rows from the combined result.
The database first applies ON to find matches. For an outer join it then adds back every preserved row that found no match, padded with NULL. Only after that does WHERE run. It sees the padded rows as ordinary rows, and it can delete them.
This is the logical order. The optimizer may execute the query differently, but it must return the same result as this order would.
A condition in WHERE removes the padding
Suppose you want every customer, along with any order over 30. Here is the first attempt, with the condition in WHERE:
SELECT c.name, o.order_id
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
WHERE o.total > 30;
-- Ada 101
-- Ben 103Cleo is missing. Step 2 produced the row Cleo, NULL, NULL. In step 3, o.total > 30 became NULL > 30, which is unknown rather than true. WHERE keeps only rows where the condition is true, so Cleo was dropped. Ada's order 102 was dropped because 20 is not above 30.
The query is now an inner join in effect. The LEFT keyword has no visible effect, because the filter throws away exactly the rows it exists to preserve.
A condition in ON limits matching only
Here is the same condition placed in ON:
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 NULLNow the condition only restricts which orders count as a match. Ada matches order 101 but not 102. Ben matches 103. Cleo matches nothing and is added back with NULL. Step 3 has no filter, so every customer survives.
A customer whose orders all fail the condition is also preserved. Use a higher threshold to see this:
SELECT c.name, o.order_id
FROM customers c
LEFT JOIN orders o
ON o.customer_id = c.customer_id AND o.total > 40;
-- Ada 101
-- Ben NULL
-- Cleo NULLBen has an order, but it is 35, so nothing matches. He appears once with NULL, exactly like Cleo. In an outer join, a NULL in the right-side columns means "no matching row under the ON condition". It does not mean "this customer has no orders at all".
Conditions on the preserved side
The preserved side of a LEFT JOIN is the left table. A condition on it behaves differently in the two clauses.
In WHERE, it filters the left rows as you would expect:
SELECT c.name, o.order_id
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
WHERE c.name = 'Ada';
-- Ada 101
-- Ada 102In ON, it does not filter the left rows at all:
SELECT c.name, o.order_id
FROM customers c
LEFT JOIN orders o
ON o.customer_id = c.customer_id AND c.name = 'Ada';
-- Ada 101
-- Ada 102
-- Ben NULL
-- Cleo NULLEvery left row is preserved no matter what ON says. Ben and Cleo fail the c.name = 'Ada' test, so they match nothing, but they still appear with NULL. This is a common source of bugs. Someone writes AND c.name = 'Ada' in ON expecting to restrict the customers, and gets all of them back.
Summary of placement
| Condition is on | In ON | In WHERE |
|---|---|---|
| Preserved side (left table of a LEFT JOIN) | Does not remove any rows. Unmatched rows get NULLs. | Removes preserved rows. |
| Optional side (right table of a LEFT JOIN) | Limits which rows can match. Preserved rows stay. | Removes NULL-padded rows too, because NULL comparisons are not true. |
| Both tables, such as a join key | Defines the match. | Turns the outer join into a different query. |
The deliberate exception: IS NULL
One WHERE filter on the optional side is correct. It is the anti-join from the earlier chapter:
SELECT c.name
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
WHERE o.order_id IS NULL;
-- CleoHere you want the padded rows, and IS NULL is the one test that is true for them. Test a column that cannot be NULL in real data, such as the primary key order_id. If you test a nullable column like o.customer_id or a nullable total, you cannot tell padding from a genuine NULL value.
A related pattern keeps unmatched rows while filtering matched ones in WHERE:
SELECT c.name, o.order_id
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
-- Ben 103
-- Cleo NULLThis looks like the ON version, but it is not equivalent in general. Use a threshold of 40 instead of 30. The WHERE form returns Ada 101 and Cleo NULL. Ben is gone, because his only order has a real total of 35 and a real order id, so neither branch is true. The ON form returned Ben with NULL. Which behavior you want depends on the question: "customers with no large orders" (ON) versus "customers with no orders, or a large one" (WHERE).
Inner joins are the safe case
For an INNER JOIN there are no preserved rows, so the two placements are interchangeable:
-- These return the same rows
SELECT c.name, o.order_id
FROM customers c
INNER JOIN orders o
ON o.customer_id = c.customer_id AND o.total > 30;
SELECT c.name, o.order_id
FROM customers c
INNER JOIN orders o ON o.customer_id = c.customer_id
WHERE o.total > 30;
-- Ada 101
-- Ben 103Many people write inner-join filters in WHERE by habit. That habit is harmless there and wrong for outer joins, so it pays to decide the placement deliberately for every outer join you write.
RIGHT and FULL joins
The rules mirror each other. In a RIGHT JOIN, the right table is preserved, so a WHERE condition on the left table's columns removes the padded rows. In a FULL OUTER JOIN, both sides are preserved, so a WHERE condition on either side's columns can remove padded rows from the other side:
SELECT c.name, o.order_id
FROM customers c
FULL OUTER JOIN orders o ON o.customer_id = c.customer_id
WHERE o.total > 30;
-- Ada 101
-- Ben 103Cleo's row has NULL for total, so it is removed. Order 104 has total 15, so it fails too. Both outer behaviors are gone. In a full join, a condition inside ON also never removes rows from either side. It only decides which pairs match.
Chained joins
When several joins are chained, a condition placed carelessly can undo an earlier outer join. Suppose you LEFT JOIN orders to customers and then INNER JOIN a third table to the orders. The inner join's ON compares a column from orders, and for Cleo that column is NULL. The comparison is not true, so Cleo's row is dropped. The earlier LEFT JOIN was cancelled by a later INNER JOIN.
Two rules avoid this:
- Once a table is on the optional side of an outer join, join anything that hangs off it with another
LEFT JOIN. - Put conditions on the optional table in the
ONof the join that introduces it, not inWHERE.
The next chapters on chaining return to this with a full example.
Choosing where a condition goes
Ask one question: should rows that fail this condition still appear in the result?
- If a failing row should still appear, with
NULLfor the optional side, put the condition inON. - If a failing row should disappear from the result entirely, put the condition in
WHERE. - If you are looking for rows with no match, use
WHERE optional_table.not_null_column IS NULL.
Summary
ONdefines which rows match.WHEREfilters the finished result, including NULL-padded rows.- A condition on the optional side in
WHEREis not true for padded rows, so they are removed. - A condition in
ONnever removes preserved rows. A left-table condition inONdoes not filter the left table. WHERE x.not_null_col IS NULLis the intended exception, and it is how the anti-join works.- For inner joins the two placements are equivalent.
Exercise
Predict the rows returned by this query. Then rewrite it so that every customer still appears, showing only orders under 30. SELECT c.name, o.orderid FROM customers c LEFT JOIN orders o ON o.customerid = c.customer_id WHERE o.total < 30;
Show answer
The query returns only one row: Ada, 102. The NULL-padded row for Cleo fails NULL < 30. Ada's order 101 (50) and Ben's order 103 (35) fail the condition. To keep every customer, move the condition into ON: LEFT JOIN orders o ON o.customer_id = c.customer_id AND o.total < 30 with no WHERE clause. The result is Ada 102, Ben NULL, Cleo NULL.