Aggregates and GROUP BY
7 pages · ~5 min✓ Reviewed
Builds on Queries and Joins. Next up: Subqueries and CTEs.
Aggregates and the Grouping Mental Model
1. Aggregates and groups
- An aggregate collapses many rows into one value
COUNT,SUM,AVG,MIN,MAX- No
GROUP BY: the whole table is one group, exactly one row GROUP BYsplits rows into buckets: one output row per bucket
sql
SELECT dept, COUNT(*) FROM emp GROUP BY dept;
| dept | COUNT(*) |
|---|---|
| Sales | 3 |
| HR | 2 |
one row per dept
2. Ungrouped columns
| Engine | Column not in GROUP BY |
|---|---|
| SQL Server | error (strict) |
| PostgreSQL, MySQL 5.7+ | ok if functionally dependent on the key |
| SQLite | bare column accepted |
Portable rule
Every non-aggregated SELECT column goes in GROUP BY, or inside an aggregate. Not an error in every engine, but safe in all.
3. Logical order
- FROM
- WHERErows
- GROUP BY
- HAVINGgroups
- SELECT
- ORDER BY
Core Aggregate Functions
1. What each one does
COUNT(*)counts rows;COUNT(col)counts non-NULL valuesSUMandAVGignore NULLsAVG=SUM/COUNT(col), not the row countMINandMAXwork on numbers, strings and dates, and ignore NULLs
| Function | NULL values | Zero rows |
|---|
WHERE vs HAVING
1. Row filter vs group filter
- FROM
- WHEREfilters rows
- GROUP BYmakes groups
- HAVINGfilters groups
- SELECT
| WHERE | HAVING | |
|---|---|---|
| Filters | rows | groups |
| Runs | before GROUP BY | after aggregation |
DISTINCT and Counting with NULLs
1. DISTINCT
SELECT DISTINCT a, bdedupes the whole row, not justaCOUNT(DISTINCT col)counts unique non-NULL values
2. Three counts, three numbers
| On 5, 5, NULL, 7 | Counts | Result |
|---|---|---|
COUNT(*) |
CASE Expressions and Conditional Aggregation
1. CASE Basics
CASE WHEN c1 THEN x WHEN c2 THEN y ELSE z END- First matching branch wins; later ones are skipped
- No
ELSE: unmatched rows return NULL
2. Conditional Aggregation
- Conditional count:
SUM(CASE WHEN status = 'paid' THEN 1 ELSE 0 END) - Pivot-style: one aggregate per output column
- Without
ELSE, non-matches are NULL andSUMskips them
Aggregates Cheat Sheet
1. Counting and NULLs
| Call | Result |
|---|---|
COUNT(*) | all rows |
COUNT(col) | non-NULL values |
COUNT(DISTINCT col) | unique non-NULL values |
SUM AVG MIN MAX | skip NULLs |
Check yourself
A dept has salaries 10, 20 and NULL. What do AVG(salary) and SUM(salary)/COUNT(*) return?
AVG(salary)is 15: 30 / 2 non-NULL valuesSUM(salary)/COUNT(*)is 10: 30 / 3 rows- AVG divides by
COUNT(col), not the row count
Spot the bug: SELECT dept, COUNT(*) FROM emp WHERE COUNT(*) > 5 GROUP BY dept;
- Aggregates are not allowed in
WHERE, which runs before grouping - Use
HAVING COUNT(*) > 5afterGROUP BY