SQL & Relational Database Mastery · Chapter 3 · ~15 min · Intermediate
Aggregations & The GROUP BY Conveyor Belt
Master multi-column grouping, HAVING filters vs WHERE clauses, COUNT(*) vs COUNT(column), and aggregate collapse mechanics.
- Understand how GROUP BY collapses multiple input rows into a single aggregated bucket
- Distinguish COUNT(*) which counts rows from COUNT(col) which ignores NULLs
- Master the strict execution boundary between WHERE (pre-filter) and HAVING (post-filter)
- Group across multiple dimensions and combine SUM, AVG, MIN, and MAX safely
Aggregations & The GROUP BY Conveyor Belt: learn it visually
Master multi-column grouping, HAVING filters vs WHERE clauses, COUNT(*) vs COUNT(column), and aggregate collapse mechanics.
1The Bucket Principle: How GROUP BY Transforms Data
In Chapters 1 and 2, every SQL query operated on individual rows. If the table had 1,000 rows, SELECT * returned 1,000 individual records.
In production business intelligence, executives don't want to read 1,000 raw sales slips. They want the total revenue per store, the average order value per month, or the headcount per department. This requires aggregation.
Think of GROUP BY as a mechanical sorting conveyor belt. It takes every row coming off the database disk, inspects its grouping key (e.g. department), drops it into that department's bucket, and collapses the bucket into a single summary row.
-- Each department collapses into 1 row, computing aggregates for all rows in that bucket
SELECT department,
COUNT(*) AS total_employees,
SUM(salary) AS total_payroll,
ROUND(AVG(salary), 2) AS average_salary,
MIN(salary) AS lowest_salary,
MAX(salary) AS highest_salary
FROM employees
GROUP BY department;What happens when you run 'SELECT department, employee_name, SUM(salary) FROM employees GROUP BY department;' in strict SQL?
2Mental Models: WHERE vs HAVING & COUNT Traps
Aggregation trips up even intermediate developers due to phase confusion. Explore the 3 crucial mental models below:
Wrong idea: Filtering aggregates inside the WHERE clause
Writing 'WHERE SUM(sales) > 1000' throws an error. The WHERE clause executes row-by-row before any groups are formed, so group aggregates do not exist yet.
Real system: WHERE filters rows early; HAVING filters collapsed groups
WHERE eliminates individual rows before grouping. After GROUP BY creates summary buckets, HAVING inspects the aggregated calculations of each bucket.
A table has 5 rows where the 'commission' column has values: [100, 200, NULL, 300, NULL]. What will 'SELECT COUNT(*), COUNT(commission) FROM sales;' return?
3Interactive Simulator: The GROUP BY Conveyor Belt
Experiment with the interactive conveyor belt below. Switch between 1-dimension and 2-dimension grouping, change the aggregate metric, and adjust the HAVING threshold to watch raw transaction rows collapse into live summary cards.
Live GROUP BY Conveyor Belt & Aggregation Engine
Compiled SQL Statement:
SELECT dept,
SUM(amount) AS total_revenue
FROM transactions
GROUP BY dept;Conveyor Belt Buckets (Collapsed Results):
Collapsed raw rows:
Collapsed raw rows:
Collapsed raw rows:
Multi-Column Grouping
Grouping by department, region creates a distinct bucket for every unique pair (e.g. "Engineering North", "Engineering South").
HAVING Execution Order
HAVING runs after aggregates compute. It filters out completed buckets that don't meet group-level criteria like HAVING COUNT(*) >= 5.
You want to find departments with more than 10 active employees. Where should 'active = TRUE' and where should 'COUNT(*) > 10' be placed?
4Bug Hunt: Fix the Regional Sales Aggregation
An automated revenue dashboard is broken with syntax errors. Fix the query by adding the missing GROUP BY, removing the unaggregated column, and properly separating row-level WHERE filters from group-level HAVING filters.
🎯 Find and fix the bugs in the code above, then press Run & verify to test your solution.
Need a hint?
• Remove employee_name from SELECT.
• Add GROUP BY department.
• Move SUM(sales_amount) > 10000 to HAVING.
5Recap & Logical Query Processing Flow
- Logical Processing Order:
FROM→WHERE→GROUP BY→HAVING→SELECT→ORDER BY→LIMIT. WHEREfilters individual records before grouping.GROUP BYcollapses raw records into discrete category buckets.HAVINGfilters group summary buckets after aggregate calculations finish.COUNT(*)tallies physical rows;COUNT(col)strictly tallies non-NULL values.
Ready for Chapter 4 (JOINs Visualized)? Mark this chapter as complete to proceed: