Summarising data
GROUP BY and HAVING
Goal: Aggregate per group and filter groups · 10 min
GROUP BY splits the rows into groups with equal values and computes aggregates per group:
SELECT category, COUNT(*) FROM products GROUP BY category;
Every selected column must either be in GROUP BY or inside an aggregate.
HAVING filters groups after aggregation, while WHERE filters rows before grouping:
SELECT city, COUNT(*) FROM customers GROUP BY city HAVING COUNT(*) >= 2;
Full logical order: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT.
Worked example: Average price per category
- Two groups: electronics, furniture.
- electronics: (900 + 25 + 80)/3 = 335.
- furniture: 490/3 ≈ 163.33.
SELECT category, ROUND(AVG(price), 2) AS avg_price
FROM products
GROUP BY category
ORDER BY category;Output:
electronics | 335.0
furniture | 163.33