SQL 101· Level 4
GROUP BY and aggregates
So far every result row has been a row from a table. Aggregate functions summarise many rows into one number.
COUNT(*)counts rows.COUNT(mark)counts only the rows where mark is not NULL.SUM,AVG,MINandMAXadd up, average, and find the smallest and largest. They all skip NULLs.ROUND(AVG(mark), 1)rounds a result to one decimal place.
GROUP BY splits the rows into groups and returns one row per group. GROUP BY state means "one row for each state".
The rule: every column in SELECT must either be listed in GROUP BY or sit inside an aggregate function.
Clause order: SELECT, FROM, WHERE, GROUP BY, ORDER BY, LIMIT. WHERE filters the rows before they are grouped.
Worked example
How many students come from each state or territory?
SELECT state, COUNT(*) AS students FROM students GROUP BY state ORDER BY students DESC
Getting the practice database ready…
This takes a few seconds the first time. Nothing leaves your computer.