GROUP BY
- Grouping. GROUP BY collapses rows sharing a value into one summary row per group: per customer, per day, per product.
- The grouping rule. Every selected column is either grouped or aggregated: the rule that explains most GROUP BY errors.
- Grouping by expressions. You can group by an expression: truncating timestamps to the day builds a daily series in one clause.
Aggregate Functions
- The core five. COUNT, SUM, AVG, MIN and MAX summarise each group: the vocabulary of every report.
- COUNT variants. Counting all rows differs from counting one column, which skips NULLs: two questions, one verb.
- Aggregates and NULL. Aggregates ignore NULL inputs, so an AVG over sparse data reflects only known values: decide if that is what you meant.
HAVING and Analytical Summaries
- HAVING. HAVING filters groups after aggregation: customers HAVING SUM(total) > 1000, where WHERE cannot reach.
- WHERE versus HAVING. WHERE trims rows before grouping, HAVING trims groups after: using the right one is also faster.
- Rollup thinking. Reports layer summaries: daily, monthly, overall: and subtotals come from grouping at several grains.
Before and after this level
- Before: Level 3: Joining Data: Inner and Outer Joins, Multi-Table Relationships, Designing Correct Joins.
- Next: Level 5: Subqueries & CTEs: Subqueries, Common Table Expressions, Breaking Complex Queries Into Stages.
In the app each of these ideas is taught and then asked back, and the level ends with a checkpoint and flashcards. See Checkpoints and flashcards.
Frequently asked questions
What does SQL Level 4: Aggregation cover?
GROUP BY, Aggregate Functions, HAVING and Analytical Summaries: 3 lessons and 9 ideas.
What should I know before this level?
The level before it, Level 3: Joining Data, which covers Inner and Outer Joins, Multi-Table Relationships, Designing Correct Joins.