Code of the Day
BeginnerQuerying basics

Aggregates and grouping

Summarise many rows into totals with COUNT/SUM/AVG, GROUP BY, and HAVING.

SQLBeginner9 min read
Recommended first
By the end of this lesson you will be able to:
  • Compute totals with COUNT, SUM, AVG, MIN, MAX
  • Summarise per group with GROUP BY
  • Filter groups with HAVING

collapse many rows into a single value. The common ones: COUNT, SUM, AVG, MIN, MAX.

SQL — editable, runs in your browser

You can mix several aggregate functions in one SELECT:

SQL — editable, runs in your browser

GROUP BY: a total per group

splits rows into groups and computes the aggregate for each. "How many customers per country?":

SQL — editable, runs in your browser

The rule: every column in SELECT must either be in the GROUP BY or wrapped in an aggregate. country is grouped; COUNT(*) is aggregated — valid.

HAVING: filter the groups

WHERE filters rows before grouping; HAVING filters groups after. "Only countries with more than one customer":

SQL — editable, runs in your browser

Order of clauses: WHERE (rows) → GROUP BYHAVING (groups) → ORDER BY. Use WHERE to cut rows early, HAVING only for conditions on the aggregates.

Where to go next

You've covered reading data. The module's lab puts it all together with graded exercises. (Changing data — INSERT/UPDATE/DELETE — is next, then the lab.)

Finished reading? Mark it complete to track your progress.

On this page