SQL · Module 03: Aggregations, GROUP BY & CASE WHENTutorial 7 of 24

3.1 Aggregate Functions (COUNT, SUM, AVG, MIN, MAX) & GROUP BY

Collapse millions of raw rows into business KPIs using COUNT, SUM, AVG, MIN, MAX, and GROUP BY — plus the #1 GROUP BY rule and how NULLs affect AVG vs COUNT.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

1. How GROUP BY Works Visually (Bucket Mental Model)

Imagine you have 10,000 employee rows and your CEO asks: "What is the average salary per department?"
GROUP BY department sorts every row into separate buckets (one bucket per department), and then runs an aggregate function (COUNT, SUM, AVG, MIN, MAX) on each bucket to produce 1 summary row per bucket.

Raw RowsEng · 120kSales · 80kEng · 140kSales · 90k→Bucket: Eng[120k, 140k]Bucket: Sales[80k, 90k]→AVG(salary)Eng → 130kSales → 85k
GROUP BY splits raw rows into buckets by key (Eng, Sales), then collapses each bucket into a single summary value.

2. The 5 Core Aggregate Functions & How They Treat NULL

FunctionWhat It ComputesIgnores NULLs?Critical Gotcha
COUNT(*)Total rows in each group❌ Counts all rowsIncludes rows with NULL values
COUNT(col)Non-NULL values in col✅ Ignores NULLCOUNT(DISTINCT col) counts unique non-NULLs
SUM(col)Total of numeric values✅ Ignores NULLReturns NULL (not 0) if ALL rows are NULL
AVG(col)SUM(col) / COUNT(col)✅ Ignores NULLHuge trap: AVG of [100, 200, NULL] is 150, NOT 100!
MIN(col) / MAX(col)Smallest / Largest value✅ Ignores NULLWorks on numbers, dates, and strings!

Interview Trap (AVG + NULL):
If 1 student got NULL (absent) and 2 students got 100 and 200:

  • AVG(score) → (100 + 200) / 2 = 150 (ignores NULL)
  • AVG(COALESCE(score, 0)) → (100 + 200 + 0) / 3 = 100 (treats absent as 0) Always clarify with your interviewer whether NULL should be excluded or treated as 0!

3. The Golden Rule of GROUP BY

Rule: Every column in SELECT that is NOT inside an aggregate function (SUM, COUNT, AVG, MIN, MAX) MUST appear in GROUP BY!

SQL
-- ❌ ERROR: 'name' is neither in GROUP BY nor inside an aggregate function!
-- Which employee's name should SQL pick for the entire 'Engineering' bucket?
SELECT department, name, AVG(salary)
FROM employees
GROUP BY department;

-- ✅ VALID: Only grouped columns + aggregated expressions in SELECT
SELECT
    department,
    COUNT(*)                     AS headcount,
    ROUND(AVG(salary), 2)        AS avg_salary,
    MIN(salary)                  AS min_salary,
    MAX(salary)                  AS max_salary,
    SUM(salary)                  AS total_payroll
FROM employees
GROUP BY department
ORDER BY avg_salary DESC;

Grouping by Multiple Columns

You can group by combinations of columns — e.g., total revenue per (city, status) pair:

SQL
SELECT
    city,
    status,
    COUNT(*)    AS order_count,
    SUM(amount) AS total_revenue
FROM orders
GROUP BY city, status
ORDER BY city ASC, total_revenue DESC;

4. Watch GROUP BY Collapse Rows Step-by-Step

Tracing WHERE → GROUP BY → SELECT → ORDER BY
Interactive SQL Execution Tracer · Step 1 of 4 (1. FROM employees)
1SELECT dept, COUNT(*) AS cnt, AVG(salary) AS avg_sal
2→FROM employees
3WHERE active = TRUE
4GROUP BY dept
5ORDER BY avg_sal DESC;
Live Table State · 1. FROM employees5 rows
namedeptsalaryactive
AaravEng120000TRUE
MeeraSales80000TRUE
KabirEng140000TRUE
RiyaSales90000TRUE
DevEng60000FALSE
What the DB engine just did: Loads all 5 employee rows from the employees table.

5. Quick Check Your Understanding

Module 3.1 Quick Quiz

Q1.A column contains the values [10, 20, NULL, 30]. What does AVG(col) return?
Q2.Why does SELECT dept, employee_name, COUNT(*) FROM employees GROUP BY dept; fail in strict SQL?

Keep Exploring: Related Lessons & Tools

All Courses →