2. Designing Tables & Combining Data
Summarizing Data: GROUP BY, Aggregates & HAVING
Turn raw rows into insights using COUNT, SUM, AVG, MIN, and MAX, understand SQL's true execution order, group cleanly with GROUP BY, and filter totals with HAVING.
- Summarize tables using COUNT, SUM, AVG, MIN, and MAX aggregate functions
- Bucket rows by category cleanly using GROUP BY alongside LEFT JOIN
- Understand SQL's clause order and when to filter with WHERE vs HAVING
Executives and product managers rarely ask: "Can you email me every individual order row from this year?" Instead, they ask: "How many orders arrived per month, what is our average cart value, and which categories generated over $1,000?"
SQL answers summary questions in milliseconds using aggregate functions paired with GROUP BY.
The 5 Essential Aggregate Functions
An aggregate function collapses multiple rows into one summary number:
| Function | What It Computes | Important Edge Behavior |
|---|---|---|
COUNT(*) | Total number of rows in the group | Includes rows with NULL values |
COUNT(column) | Number of rows where column is NOT NULL | Safely skips missing values and empty LEFT JOIN rows |
SUM(column) | Adds all numeric values together | Ignores NULL values automatically |
AVG(column) | Mean average of non-NULL numbers | Wrap with ROUND(AVG(...), 2) for clean display |
MIN(col) / MAX(col) | Smallest or largest value | Works on numbers, dates (MAX(created_at)), and strings |
Bucketing Rows with GROUP BY
Calling COUNT(*) alone collapses the entire table into 1 single number. Adding GROUP BY tells SQL: "Split the rows into separate buckets first, then run the aggregate function inside each bucket."
Suppose we want to count how many students enrolled in every course—including new courses with 0 enrollments:
SELECT
c.title AS course_title,
COUNT(e.id) AS total_enrollments
FROM courses c
LEFT JOIN enrollments e ON e.course_id = c.id
GROUP BY c.id, c.title
ORDER BY total_enrollments DESC;Notice the strict golden rule of GROUP BY: every non-aggregated column in SELECT (c.id, c.title) must also appear inside GROUP BY.
Because LEFT JOIN keeps an unmatched course alongside a placeholder row filled with NULLs, COUNT(*) mistakenly counts that empty placeholder row as 1! Always pass the right-hand primary key (COUNT(e.id)) so a course with zero students accurately reports 0.
Filtering Raw Rows (WHERE) vs Filtering Groups (HAVING)
Understanding the order SQL actually executes your query clears up WHERE vs HAVING forever:
FROM/JOIN— gather and combine source rowsWHERE— throw away individual rows that don't match before groupingGROUP BY— fold remaining rows into summary bucketsHAVING— throw away summary groups based on aggregated metrics (COUNT,SUM,AVG)SELECT->ORDER BY->LIMIT— format columns, sort final results, and cap row count
Writing WHERE COUNT(e.id) >= 2 throws a syntax error because WHERE runs in step 2 before GROUP BY creates any counts! Always filter grouped totals inside HAVING instead.
Try It Yourself: Live SQL Playground
Run the enrollment report below first, then add HAVING COUNT(e.id) >= 2 right below GROUP BY to keep only popular courses:
Click “Run Code” to execute this snippet right in your browser.
Quick Checkpoints
Which clause filters grouped totals AFTER GROUP BY has run?
When counting enrollments per course using FROM courses c LEFT JOIN enrollments e, why should you write COUNT(e.id) instead of COUNT(*)?