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.
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.
2. The 5 Core Aggregate Functions & How They Treat NULL
| Function | What It Computes | Ignores NULLs? | Critical Gotcha |
|---|---|---|---|
COUNT(*) | Total rows in each group | ❌ Counts all rows | Includes rows with NULL values |
COUNT(col) | Non-NULL values in col | ✅ Ignores NULL | COUNT(DISTINCT col) counts unique non-NULLs |
SUM(col) | Total of numeric values | ✅ Ignores NULL | Returns NULL (not 0) if ALL rows are NULL |
AVG(col) | SUM(col) / COUNT(col) | ✅ Ignores NULL | Huge trap: AVG of [100, 200, NULL] is 150, NOT 100! |
MIN(col) / MAX(col) | Smallest / Largest value | ✅ Ignores NULL | Works on numbers, dates, and strings! |
Interview Trap (
AVG+NULL):
If 1 student gotNULL(absent) and 2 students got100and200:
AVG(score)→(100 + 200) / 2 = 150(ignoresNULL)AVG(COALESCE(score, 0))→(100 + 200 + 0) / 3 = 100(treats absent as0) Always clarify with your interviewer whetherNULLshould be excluded or treated as0!
3. The Golden Rule of GROUP BY
Rule: Every column in
SELECTthat is NOT inside an aggregate function (SUM,COUNT,AVG,MIN,MAX) MUST appear inGROUP BY!
-- ❌ 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:
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
| name | dept | salary | active |
|---|---|---|---|
| Aarav | Eng | 120000 | TRUE |
| Meera | Sales | 80000 | TRUE |
| Kabir | Eng | 140000 | TRUE |
| Riya | Sales | 90000 | TRUE |
| Dev | Eng | 60000 | FALSE |
5. Quick Check Your Understanding
Module 3.1 Quick Quiz
Keep Exploring: Related Lessons & Tools
All Courses →Paste any Python, JS, Java, or C++ snippet to estimate Time & Space complexity, or enter input size N to see which algorithms pass in 1s.
Test regular expressions live with color-coded match highlights, capture group inspection, plain-English token breakdown, find-and-replace, and Python/JS snippets.