WHERE or HAVING?
You'll often use both. WHERE decides which rows go into the groups; HAVING decides which
groups come out:
SELECT customer_id, COUNT(*) AS completed_orders
FROM orders
WHERE status = 'Completed' -- only completed orders are counted
GROUP BY customer_id
HAVING COUNT(*) > 30 -- only customers with more than 30 of themA quick test: if the condition is about one row (this order's status), it's WHERE. If it's about
a whole group (how many, how much in total), it's HAVING.
The clauses always come in this order: SELECT … FROM … WHERE … GROUP BY … HAVING … ORDER BY.