r/learnSQL • u/Possible_Seaweed_916 • 4h ago
Quick SQL puzzle. Why does this LEFT JOIN lose the customer with no orders?
There are two customers. Customer 1 has one paid order. Customer 2 has no orders.
I want both customers in the result, with paid order details where available.
SELECT c.id, o.status
FROM customers AS c
LEFT JOIN orders AS o
ON c.id = o.customer_id
WHERE o.status = 'paid';
This only returns customer 1. My first instinct would be to look at the join, but the row actually disappears because of the WHERE clause.
The fix here is to move o.status = 'paid' into the ON condition and remove the WHERE clause. That way the join looks for a paid order, and customer 2 still shows up with NULL for status.
5
u/SurvivalistGeek 3h ago edited 3h ago
It customer 2 has no orders, their customer_id would not even exist in the orders table right?
So when you do the left join, the rows with customer 2 will have NULL for the orders table columns, which in this case is o.status.
And when you add the WHERE clause, that row gets filtered out.
Remember that in a left join, all the left table rows are in the resultset, irrespective of join condition being true or false.
Since you want paid orders, for which that customer details have to exist in both tables, just do an inner join?
I think this is what's happening. Please correct me if I am wrong.
2
u/allhaildre 2h ago
WHERE happens after the JOIN and operates on the resulting joined table
1
u/QPGMR_de 1h ago
Understanding NULL is maybe the first hard part of learning SQL.
NULL as a value doesn't mean ZERO, it also doesn't mean NOTHING - it means UNKNOWN. So NULL is not equal to anything else - not even "another" NULL.
So selecting
o.status = 'paid'will not select the customer without an order as all order columns are NULL there. So the solution is:If you want only customers with paid orders - and for customers without a paid order no order at all, it can be done in the LEFT JOIN itself:
1
u/Professional_End4433 1h ago
Tbh with you this exercise is useless today. Ai answers stuff like this. The most important thing you could study would be how to address business questions with data.
1
u/Ok_Carpet_9510 58m ago edited 31m ago
In the WHERE clause add: OR o.id IS NULL
1
u/i_literally_died 44m ago
Putting a WHERE condition from the LEFT JOINed table collapses it to an INNER JOIN (the WHERE precludes NULLs).
Put it in the join