TutreNews Learn

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

  1. Two groups: electronics, furniture.
  2. electronics: (900 + 25 + 80)/3 = 335.
  3. 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