HAVING
ELI5 — The Vibe Check
HAVING is like WHERE but it filters after GROUP BY aggregation. WHERE filters rows before grouping, HAVING filters groups after. 'Show me users who have made MORE than 5 orders' — that is a HAVING job.
Real Talk
HAVING filters the results of GROUP BY aggregations. Because WHERE is evaluated before aggregation, it cannot filter on aggregate values like COUNT(*) or SUM(). HAVING is evaluated after GROUP BY and can reference aggregate functions in its conditions.
Show Me The Code
SELECT user_id, COUNT(*) AS order_count
FROM orders
GROUP BY user_id
HAVING COUNT(*) > 5; -- Can't use WHERE here
When You'll Hear This
"Use HAVING to filter groups, not WHERE." / "HAVING COUNT(*) > 0 to exclude empty groups."
Related Terms
GROUP BY
GROUP BY collapses rows with the same value into one group so you can count, sum, or average them. 'How many orders per user?' — GROUP BY user_id.
SELECT
SELECT is how you ask a database to give you data. It is the 'Read' in CRUD.
WHERE
WHERE is how you filter which rows a query affects. Without WHERE, SELECT returns everything, UPDATE changes everything, DELETE deletes everything.