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.

3 min readUpdated 2026-11-29
In This Lesson
  • 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:

FunctionWhat It ComputesImportant Edge Behavior
COUNT(*)Total number of rows in the groupIncludes rows with NULL values
COUNT(column)Number of rows where column is NOT NULLSafely skips missing values and empty LEFT JOIN rows
SUM(column)Adds all numeric values togetherIgnores NULL values automatically
AVG(column)Mean average of non-NULL numbersWrap with ROUND(AVG(...), 2) for clean display
MIN(col) / MAX(col)Smallest or largest valueWorks 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:

sql
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.

COUNT(*) vs COUNT(e.id) Inside LEFT JOIN

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:

  1. FROM / JOIN — gather and combine source rows
  2. WHERE — throw away individual rows that don't match before grouping
  3. GROUP BY — fold remaining rows into summary buckets
  4. HAVING — throw away summary groups based on aggregated metrics (COUNT, SUM, AVG)
  5. SELECT -> ORDER BY -> LIMIT — format columns, sort final results, and cap row count
Never Put COUNT() or SUM() Inside WHERE

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:

SQL (SQLite)Live SQL: GROUP BY & HAVING
Output

Click “Run Code” to execute this snippet right in your browser.

Quick Checkpoints

Check Your Understanding

Which clause filters grouped totals AFTER GROUP BY has run?

Check Your Understanding

When counting enrollments per course using FROM courses c LEFT JOIN enrollments e, why should you write COUNT(e.id) instead of COUNT(*)?