r/learnSQL • • 8h 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.

0 Upvotes

18 comments sorted by

11

u/SurvivalistGeek 7h ago edited 7h 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.

4

u/Flying_Saucer_Attack 7h ago

Yeah pretty sure that's it

1

u/TomWickerath 7h ago

Hmm….I haven’t tried a quickie test, but I wonder if this WHERE clause would work?

WHERE o.status = ‘paid’ OR o.status is null;

If that doesn’t work, I’d try a Union query.

1

u/leogodin217 3h ago

I think that would work, but it would be clearer to move the where condition to the on condition in the join.

4

u/allhaildre 6h ago

WHERE happens after the JOIN and operates on the resulting joined table

0

u/mariana_kl 4h ago edited 7m ago

I think SQL reads from the bottom up and filters records with where conditions before joining so it's faster.

ETA: want to clarify I'm referring to predicate pushdown, where the optimizer moves a filter predicate down into the initial table or index scan to pass fewer rows to the join whenever the logic permits. In OP’s puzzle, there are two predicates:

  • Join predicate: c.id = o.customer_id
  • Filter predicate: o.status = 'paid'

Because o.status = 'paid' rejects NULLs, SQL converts the LEFT JOIN to an INNER JOIN and evaluates that filter predicate during the scan of orders. So remove the WHERE clause and move o.status = 'paid' up to the ON clause to preserve the spirit of LEFT JOIN: LEFT JOIN on c.id = o.customer_id AND o.status = 'paid'.

Or even better, do one thing at a time:

WITH paid_orders AS ( 
SELECT customer_id, status 
FROM orders 
WHERE status = 'paid' 
) 

SELECT a.id
     , b.status 
FROM customers a 
LEFT JOIN paid_orders b 
ON a.id = b.customer_id

1

u/leogodin217 3h ago

I wouldn't be shocked to see that in a few engines, but that would either be an intentional step away from ANSI SQL or an optimization bug

1

u/jshine13371 1h ago

That's not true. SQL engines are free to make a choice to filter it at any point of execution, as long as the end results are logically correct. This allows the engine to come up with a reasonably performant execution plan that's specific to the data. 

In some cases filtering by the WHERE clause early in execution is more efficient, in other cases, joining first and filtering on the WHERE clause later might be more efficient (depending on the data, indexes, and code specifically, etc).

3

u/i_literally_died 5h 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

 LEFT JOIN orders o
 ON c.id = o.customer_id
 AND o.status - 'paid'

2

u/Discordbothost 3h ago

Add a customer with only an unpaid order to your test. Customer 3 with one 'pending' order disappears with WHERE status = 'paid' OR status IS NULL, because the join found a non-null match. Filtering in ON keeps customer 3, with NULL order columns.

1

u/QPGMR_de 5h 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:

WHERE o.status = 'paid' OR o.status IS NULL

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:

LEFT JOIN orders AS o
ON c.id = o.customer_id AND o.status = 'paid';

1

u/Ok_Carpet_9510 5h ago edited 4h ago

In the WHERE clause add: OR o.id IS NULL

1

u/8dot30662386292pow2 3h ago

For me the question seems a bit odd. We do left join to get even the customers without orders. Then out of those we only want the paid orders. What's the point? The customers without orders obviously don't have paid orders.

Though this obviously changes if we wanna count paid/total orders and want to hsve the 0/0 results as well.

1

u/Ok_Carpet_9510 2h ago

There could be some business rationale for it. A manager could have asked for this list. They could be two separate requests which OP wants to dump in one output rather two. Who knows?

-2

u/Professional_End4433 5h 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.

2

u/novicelife 3h ago

I was asked a question in FAANG interview just 2 weeks ago where this exact logic was needed to solve the question asked.