×

sql · level 2 · unit 3 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

After a LEFT JOIN, count a column, not *.

How many orders has each customer made, Sam included? A LEFT JOIN keeps Sam, so grouping by name gives Sam a group. But that group still holds one row: Sam paired with NULLs.

COUNT(*) counts rows, so Sam would get 1. That is an , because Sam has made no orders. COUNT(o.id) skips NULL boxes, so Sam gets 0.

SUM over nothing but NULLs gives NULL, not 0. You will learn to swap that for 0 soon.

SELECT c.name, COUNT(o.id) AS orders
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id
GROUP BY c.name
ORDER BY orders DESC, c.name;

Count a column from the right-hand table, ideally its id, which is only empty when there was no match.