
why COUNT(*) and COUNT(o.id) aren't the same after a LEFT JOIN
say you have customers on the left and orders on the right.
a LEFT JOIN keeps every customer, even if they have no matching order. for those rows, the columns from orders are NULL.
that creates a small gotcha which i saw a few players falling for in their queries:
-COUNT(*) counts the joined row.
-COUNT(o.id) only counts rows where o.id isn't NULL.
so this:
customer | order_id
Alice | NULL
Bob | 123
Bob | 456
becomes:
COUNT(*) | COUNT(o.id)
Alice 1 | 0
Bob 2 | 2
I made a 43 sec chalkboard animation showing the join happen visually:
https://www.youtube.com/watch?v=zxSZFMtyheA
is this helpful? i could try making a few more then.