r/learnSQL • u/Possible_Seaweed_916 • 20m 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.