Skip to content

Chapter 3 of 7

Aggregating and Grouping Data

Aggregation compresses many rows into summary values. The standard aggregate functions are COUNT, SUM, AVG, MIN, and MAX; COUNT totals the number of rows (or non-NULL values in a specific column), SUM and AVG work on numeric columns, and MIN and MAX work across most comparable types. Aggregates ignore NULL values by default, which is usually what you want but can occasionally mislead — for example, the average of a column with many missing entries may not represent the population you intended to summarize.

The GROUP BY clause collapses rows that share values in the listed columns into single output rows, which is the prerequisite for using aggregate functions meaningfully on each group. Once rows have been grouped, the HAVING clause filters those groups, in contrast to WHERE which filters individual rows before grouping. This is why you can reference an aggregate like SUM(amount) in HAVING but not in WHERE. When no GROUP BY is present, HAVING still works: the entire result set is treated as a single implicit group, so HAVING can filter on aggregate calculations of all rows together. COUNT has subtle variants worth noting — COUNT(*) counts every row, COUNT(column) counts only non-NULL values in that column, and COUNT DISTINCT counts unique non-NULL values.

For richer summaries, SQL provides GROUPING SETS, ROLLUP, and CUBE. GROUPING SETS let you compute multiple groupings in a single query — equivalent to taking the UNION of several GROUP BY queries, but more efficient. ROLLUP produces hierarchical subtotals (such as year, then year+month, then a grand total), while CUBE generates every possible combination of the grouped columns. Together, these constructs support cross-tabulation and multi-level reporting without writing multiple separate queries.

All chapters
  1. 1Foundations of SELECT
  2. 2Joining Tables
  3. 3Aggregating and Grouping Data
  4. 4Window Functions
  5. 5Subqueries, CTEs, and Set Operations
  6. 6Operators, Expressions, and Type Handling
  7. 7Schema, Performance, and Data Integrity

Drill it

Reading is not remembering. These come from the SQL For Data Analysis deck:

Q

What does SQL stand for?

Structured Query Language

Q

What is the purpose of the SELECT statement in SQL?

To query and retrieve data from one or more tables

Q

Which clause in a SELECT statement filters rows before grouping?

WHERE

Q

Which clause in a SELECT statement filters groups after aggregation?

HAVING