12/30
Part 3 of 5 · NULLs and joinsLearn and do
Put the condition in ON, where it picks which orders match
The fix moves the condition into ON, next to the key. ON can hold more than the key. Here it attaches only the SPRING orders, and every customer stays:
SELECT c.name, COUNT(o.order_id) AS spring_orders
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.customer_id
AND o.promo = 'SPRING'
GROUP BY c.customer_id, c.name
ORDER BY c.customer_id;
| name | spring_orders |
|---|---|
| Ana | 0 |
| Ben | 1 |
| Cy | 0 |
| Dee | 0 |
Put the March range in ON the same way, and the March question comes out right:
| name | march_orders |
|---|---|
| Ana | 2 |
| Ben | 1 |
| Cy | 1 |
| Dee | 0 |
The rows each version groups, side by side:
| Range in WHERE: join every order, then cut | |
|---|---|
| Ana, 10, 2026-03-02 | kept |
| Ana, 11, 2026-03-02 | kept |
| Ben, 12, 2026-03-15 | kept |
| Cy, 13, 2026-03-31 | kept |
| Cy, 14, 2026-04-01 | cut |
| Dee, NULL | cut |
| 3 customers left |
| Range in ON: attach only the March orders | Count |
|---|---|
| Ana, 10 and 11 | 2 |
| Ben, 12 | 1 |
| Cy, 13 | 1 |
| Dee, NULL | 0 |
| 4 customers left |
In ON, the condition decides which orders match. In WHERE, it decides which rows survive. This isn't a SQLite quirk. PostgreSQL's manual says the same: a condition in ON is applied before the join and one in WHERE after it, which doesn't matter for an inner join and matters a lot for an outer one.
In the editor, fix MARCH_ORDERS: every customer, with Dee's 0.