Gomaa Intelligence.Data Hub
عربي

Foundations › SQL › Aggregation & Analysis

Aggregation & Analysis

GROUP BY and HAVING: Aggregating by Groups

Lesson 10 / 14· 10 min

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.

▶ Try it yourself

Customers per city. Open in SQL Lab

▶ Try it yourself

Several aggregates in one query. Open in SQL Lab

HAVING filters groups

▶ Try it yourself

HAVING filters after grouping, so it can use aggregates. Open in SQL Lab

WHEREHAVING
Works onRows before groupingGroups after grouping
Can use aggregates?NoYes
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.

Exercise 2 — Show categories whose average product price exceeds 400: category and avg_price.

Exercise 3 — Show customers who joined since 2026 began, per city, sorted by count descending then city: city and n.

Summary
  • 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.

Get your data analyzed by an expert ↗