The join is part of FROM. It runs first. WHERE, GROUP BY and HAVING then work on the joined rows, in the order you know from Chapter 7.
How many items does each order have? Join, then group:
sql
SELECT o.id, COUNT(*) AS items
FROM orders o
JOIN order_items oi ON oi.order_id = o.id
GROUP BY o.id;FROM … JOIN
WHERE
GROUP BY
HAVING
SELECT
Count 0 with a left join
Count the employees in each department, Legal included:
sql
SELECT d.name, COUNT(*) AS staff
FROM departments d
LEFT JOIN employees e ON e.department_id = d.id
GROUP BY d.id, d.name;the joined rows of Legal
| d.name | e.id | e.name |
|---|---|---|
| Legal | NULL | NULL |
COUNT(*) counts rows, so Legal gets 1. That is wrong. Count a column of the right table that is never NULL in a real match:
sql
SELECT d.name, COUNT(e.id) AS staff
FROM departments d
LEFT JOIN employees e ON e.department_id = d.id
GROUP BY d.id, d.name;COUNT(e.id) skips NULL (Chapter 7), so Legal gets 0.