Video in progress

Explain the difference between WHERE and HAVING.

WHERE filters individual rows before grouping, while HAVING filters the finished groups after GROUP BY. That's why a condition on an aggregate function (COUNT, SUM) can only go in HAVING.

📖 Answer

SELECT user_id, count(*) AS cnt
FROM orders
WHERE status = 'PAID'          -- first every row is checked
GROUP BY user_id
HAVING count(*) >= 3;          -- then the groups are checked

This query returns "users with at least 3 paid orders".

If you write WHERE count(*) >= 3, you get an error: when WHERE runs, the groups don't exist yet.

A practical tip: put row-level conditions in WHERE, not in HAVING. HAVING status = 'PAID' sometimes works too (if status is in the GROUP BY), but then the database groups all the rows first and throws some away afterward, which is wasted work.