Foundations › SQL › Aggregation & Analysis
Aggregation & AnalysisGROUP BY and HAVING: Aggregating by Groups
GROUP BY splits rows into groups by one or more columns and applies the aggregate to each group. It is the equivalent of a PivotTable in Excel.
Customers per city. Open in SQL Lab
Several aggregates in one query. Open in SQL Lab
HAVING filters groups
HAVING filters after grouping, so it can use aggregates. Open in SQL Lab
| WHERE | HAVING | |
|---|---|---|
| Works on | Rows before grouping | Groups after grouping |
| Can use aggregates? | No | Yes |
For advanced readers Execution order and advanced grouping
Because WHERE runs before GROUP BY, filter as much as you can there to shrink rows before grouping. Other dialects offer ROLLUP, CUBE and GROUPING SETS for subtotals in one query.
Exercise 1 — Show the number of orders per status: columns status and n.
GROUP BY status with COUNT(*).
Exercise 2 — Show categories whose average product price exceeds 400: category and avg_price.
Use HAVING AVG(price) > 400.
Exercise 3 — Show customers who joined since 2026 began, per city, sorted by count descending then city: city and n.
Filter with WHERE, then GROUP BY, then ORDER BY n DESC, city.
- GROUP BY splits into groups and summarizes each.
- WHERE filters rows before grouping and HAVING filters groups after.
- SELECT columns are either in GROUP BY or inside an aggregate.
Want an expert to do it for you?
Gomaa Intelligence turns your data into clear reports and decisions. Tell us your problem and we will reply.