Module F-4·18 min read

COUNT, SUM, AVG, GROUP BY, HAVING — the mental model that confuses beginners, explained from scratch.

JJS
Written by Jatin Jain Saraf · Senior Software Engineer

F-4 — Aggregation — Summarising Your Data

Who this module is for: You completed F-3 and can filter and sort individual rows. Now you need to answer questions about groups of rows — "how many products are in each category?", "what is the average price?", "which categories have more than 5 products?". This module covers aggregation — the most conceptually tricky part of SQL for beginners.


The Problem Aggregation Solves

So far, every query has returned rows from the table — one row of output per row of input (or fewer after filtering). Aggregation is different: it collapses multiple rows into a single summary value.

text

Aggregate Functions

These functions take a column of values and return a single summary value:

sql

When you use an aggregate function without GROUP BY, it collapses the entire table into a single row:

sql

GROUP BY — The Mental Model

GROUP BY is where most beginners get confused. The mental model:

  1. PostgreSQL divides all your rows into groups based on the column(s) you specify
  2. Each group is collapsed into a single output row
  3. You can then apply aggregate functions to each group separately
sql

Visualise what happens:

text

The Golden Rule of GROUP BY

Every column in your SELECT list must either be in the GROUP BY clause OR be wrapped in an aggregate function.

sql

This error trips up beginners constantly. The reason: if you group by category, and there are 3 rows in the "peripherals" group, which name value should PostgreSQL return? There are three of them. It cannot pick one arbitrarily — so it forces you to either group by name too (making each row unique) or use an aggregate.

Multiple columns in GROUP BY

sql

When you GROUP BY multiple columns, each unique combination of those columns becomes one output row.


Common Aggregation Patterns

sql

HAVING — Filtering Groups

WHERE filters individual rows before grouping. HAVING filters groups after aggregation.

sql

Sign in to keep reading

The rest of this module is free — sign in with Google to unlock it and track your progress.

Sign in & Register

Discussion

0

Join the discussion

Loading comments...

© 2026 Jatin Jain Saraf (JJS). All rights reserved.