Chapter 3 of 12
Course Progress0 of 12 completed (0%)

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.

Aggregations & The GROUP BY Conveyor BeltMaster multi-column grouping, HAVING filters vs WHERE clauses, COUNT(*) vs COUNT(column), and aggregate collapse mechanics.UNDERSTANDAggregationsFOLLOW THE FLOWGROUP Conveyor BeltAPPLY ITmulti-columngroupingAggregations & The GROUP BY Conveyor BeltMaster multi-column grouping, HAVING filters vs WHERE clauses, COUNT(*) vs COUNT(column), and aggregate collapse mechanics.UNDERSTANDAggregationsFOLLOW THE FLOWGROUP Conveyor BeltAPPLY ITmulti-columngrouping

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;
Concept Check

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

FROM sales → WHERE SUM(amount) > 1000
❌ Crash: Aggregate function not allowed in WHERE

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

FROM → WHERE status='paid' → GROUP BY dept → HAVING SUM(amount) > 1000
✅ Pipeline order: Raw rows filtered → Bucketed → Aggregates filtered

WHERE eliminates individual rows before grouping. After GROUP BY creates summary buckets, HAVING inspects the aggregated calculations of each bucket.

Concept Check

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

3 bucket(s) generated

Compiled SQL Statement:

SELECT dept,
       SUM(amount) AS total_revenue
FROM transactions
GROUP BY dept;

Conveyor Belt Buckets (Collapsed Results):

Engineering
3 raw row(s)
Total Revenue (SUM):$1,350
Average Sale (AVG):$450
COUNT(*) [Rows]:3
COUNT(bonus) [Non-null]:2

Collapsed raw rows:

#101: $450 (+$50)#102: $300 (no bonus)#103: $600 (+$100)
Sales
3 raw row(s)
Total Revenue (SUM):$2,150
Average Sale (AVG):$717
COUNT(*) [Rows]:3
COUNT(bonus) [Non-null]:2

Collapsed raw rows:

#104: $800 (+$120)#105: $950 (+$150)#106: $400 (no bonus)
Marketing
2 raw row(s)
Total Revenue (SUM):$600
Average Sale (AVG):$300
COUNT(*) [Rows]:2
COUNT(bonus) [Non-null]:1

Collapsed raw rows:

#107: $250 (+$40)#108: $350 (no bonus)

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.

Concept Check

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.

SQL Bug Hunt · Department Sales Aggregation
SQL

🎯 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.
  • WHERE filters individual records before grouping.
  • GROUP BY collapses raw records into discrete category buckets.
  • HAVING filters 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:

Enjoying this free lesson? Your support helps us build more free animated chapters.

Support Us