Skip to main content

Chapter 4 · Aggregations

SQL GROUP BY Practice

Aggregations turn many rows into one answer: total revenue, average order value, number of customers per state. GROUP BY splits the rows into groups and computes one result per group.

This is where most analyst questions live. Learn when to filter with WHERE (before grouping) versus HAVING (after grouping), and how COUNT(*) differs from COUNT(column).

Start practising74 exercises · 45 easy, 27 medium, 2 hard

Key ideas

COUNT, SUM, AVG, MIN, MAX
Summarise a column. COUNT(*) counts rows; COUNT(col) skips NULLs.
GROUP BY
One output row per group. Every selected column must be grouped or aggregated.
HAVING
Filter groups after aggregating, e.g. only states with more than 10 customers.
ROUND
Round averages and money for readable results: ROUND(AVG(x), 2).

Example: Orders and average order value by status

SELECT status,
       COUNT(*) AS orders,
       ROUND(AVG(total_amount), 2) AS avg_order
FROM orders
GROUP BY status
HAVING COUNT(*) > 50
ORDER BY orders DESC;

GROUP BY makes one row per status; HAVING then drops statuses with 50 orders or fewer.

In interviews

"WHERE or HAVING?" comes up constantly. WHERE filters rows before grouping; HAVING filters the groups. Filtering early with WHERE is also faster.

All 74 Aggregations exercises

Ordered from easiest to hardest. Each one runs on a real database with instant feedback.