Video in progress

This query was supposed to show users with no orders too, but it doesn't. Where is the mistake?

SELECT u.email, count(o.id) AS paid_orders
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
WHERE o.status = 'PAID'
GROUP BY u.email;

The condition on the right table's column sits in WHERE. For rows with no matching order, o.status is NULL, NULL = 'PAID' isn't true, and those rows are dropped, so the LEFT JOIN effectively becomes an INNER JOIN. The condition has to move into ON.

📖 Answer

Remember the order: first the JOIN builds the rows, then WHERE filters them. For a user with no orders, the LEFT JOIN produces a row where the o.* columns are NULL, and then WHERE o.status = 'PAID' removes it.

The correct version:

SELECT u.email, count(o.id) AS paid_orders
FROM users u
LEFT JOIN orders o
       ON o.user_id = u.id
      AND o.status = 'PAID'      -- the condition is part of the join
GROUP BY u.email;

Now every user shows up, and users with no paid orders get paid_orders = 0.

The rule is simple:

  • ON: "which right-side rows get paired";
  • WHERE: "which rows stay in the final result".

With an INNER JOIN it makes no difference where you put the condition, but with a LEFT JOIN it makes a big difference. This mistake comes up a lot in review, because the query runs without errors, and if every user in the test data has an order, you won't notice it at all. So add the "has nothing" case to your tests too.