SQL Basics: Ask Questions of Data
Summarising Data: COUNT, SUM, GROUP BY
In this lesson you will
- Use COUNT, SUM, AVG, MIN and MAX
- Group rows with GROUP BY
- Filter groups with HAVING
Introduction
So far each result row came from one table row. Often you want a summary instead: how many products, the average price, the total stock. Functions that squash many rows into one value are called aggregate functions.
The five aggregate functions
COUNT(*)counts rows.SUMadds values,AVGaverages them.MINandMAXfind the smallest and largest.
They respect WHERE, which filters rows before they are summarised:
COUNT(column) counts only rows where that column is not NULL, while COUNT(*) counts all rows. Compare them:
Quick quiz
Why can COUNT(city) be smaller than COUNT(*) for the same table?
GROUP BY: one answer per group
GROUP BY splits rows into groups and gives one result row per group. This answers "for each category, ...".
A rule to remember: every column in SELECT must either be in the GROUP BY or be wrapped in an aggregate function.
HAVING: filter the groups
WHERE filters rows before grouping. HAVING filters groups after the summary is calculated. Use it when the condition involves an aggregate.
The full clause order is:
SELECTFROMWHERE(rows)GROUP BYHAVING(groups)ORDER BYLIMIT
Quick quiz
Which clause filters groups using a result like COUNT(*)?
Put it together
Which categories have a total stock above 150 units, with the biggest first?
Try it yourself
For each customer city, count how many customers live there. Leave out customers whose city is missing, and show the largest cities first.
Summary
COUNT,SUM,AVG,MINandMAXturn many rows into one value.COUNT(*)counts all rows.COUNT(column)skips NULLs.GROUP BYgives one result row per group.WHEREfilters rows before grouping, andHAVINGfilters groups after.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading