GROUP BY and HAVING
099 min
GROUP BY splits rows into groups that share a value and calculates for each group separately. “How many students come from each city?”, “what is the average price in each category?” — that is GROUP BY.
How it works
The database sorts the students into “piles” by city and then counts each pile. Each city becomes one row of the result.
The rule
Every column in SELECT must either appear in GROUP BY or sit inside an aggregate:
PostgreSQL always enforces this rule: break it and you get “must appear in the GROUP BY clause”.
HAVING — a condition on groups
WHERE filters rows before grouping; HAVING filters groups after:
Both together:
The order of execution
A query is written in this order, and the database runs it in nearly the same order:
FROM— which table;WHERE— which rows;GROUP BY— grouping;HAVING— which groups;SELECT— what to show;ORDER BY,LIMIT— order and limit.
That is why COUNT(*) cannot be used in WHERE — at that step there are no groups yet.
Show the number of orders for each status: the status and the count.
Show the brands that have at least 4 products: brand and the number of products.
Show the total amount of payments for each payment method.
Remember
GROUP BYcalculates per group; plain columns inSELECTmust be inGROUP BY.WHEREis for rows,HAVINGis for groups.- Order:
FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY.