SQSQL · Lesson 4 of 8
COUNT, SUM & GROUP BY
So far every query returned rows as-is. Aggregate functions collapse many rows into one answer: how many students? What's the average grade? GROUP BY asks that per category.
GROUP BY splits rows into buckets and runs the aggregate per bucket. 'Average grade per age' means: bucket rows by age, then AVG each bucket. Every selected column must either be in the GROUP BY or wrapped in an aggregate — otherwise the database can't know which row's value to show.
✦ Tip
Remember the execution order: WHERE runs before grouping (it can't see aggregates), HAVING runs after (it can). If you catch yourself writing WHERE AVG(grade) > 85, you want HAVING.
Remember the execution order: WHERE runs before grouping (it can't see aggregates), HAVING runs after (it can). If you catch yourself writing WHERE AVG(grade) > 85, you want HAVING.