Reading Room · Module 04
Track 0/9 (0%)
Course completion
Module 04 · Aggregation~20 min · 6 worked queries

Grouping, Folding & HAVING Filters

Collapse surviving rows into keyed buckets with GROUP BY, distinguish COUNT(*) from COUNT(col), and filter post-fold buckets with HAVING.

Trace Live in StudioAll Modules
Core Relational Rule
WHERE discards individual tuples before grouping; GROUP BY folds N tuples per key into 1 summary row; HAVING discards whole buckets afterward.Module 04 · Aggregation · Reading Room

Mental Model

  1. 01.

    Every non-aggregated column in SELECT must belong to the GROUP BY key list so group identity stays unambiguous.

  2. 02.

    COUNT(*) counts rows in the bucket including NULLs; COUNT(col) counts only rows where col IS NOT NULL.

  3. 03.

    Conditional aggregation — SUM(CASE WHEN ... THEN 1 ELSE 0 END) — computes pivot counts inside a single scan.

Frequent Pitfall to Avoid
Confusing WHERE and HAVING: placing non-aggregate conditions in HAVING wastes work, while putting aggregates in WHERE fails parsing.

Interactive Module Lab · Aggregations

22. HAVING filters groups — sql
SELECT department_id, COUNT(*) AS total_staff, AVG(salary) AS avg_salary
FROM users
WHERE department_id IS NOT NULL
GROUP BY department_id
HAVING COUNT(*) > 1;
Execution Stages4 steps
Stage 01 · FROM

SOURCE: USERS

10 in → 10 out

Scanned 10 rows from table 'users'.

#idnamedepartment_idrolesalarystate
11Alice Smith1Software Engineer95,000keep
22Bob Jones2Product Manager110,000keep
33Charlie Lee1Software Engineer88,000keep
44Diana Prince3UX Designer76,000keep
55Evan Wright2Data Analyst82,000keep
66Fiona Gallagher1Tech Lead135,000keep
77George ClarkNULLIntern42,000keep
88Hannah Abbott2Scrum Master89,000keep
Inspect each evaluated clause in 22. HAVING filters groups or animate every row moving between stages in Studio.Open 22. HAVING filters groups in Studio →

Worked Presets in This Module

20. COUNT(*) vs COUNT(column)

COUNT(*) counts rows; COUNT(column) skips NULLs; COUNT(DISTINCT ...) skips repeats. No GROUP BY means one group.

21. GROUP BY & Aggregations

Rows are sorted into buckets by department, then each bucket collapses into a single summary row.

22. HAVING filters groups

WHERE filters rows before grouping. HAVING filters whole groups after aggregation.

23. Grouping by two columns

A bucket is now each distinct (country, department) pair.

24. Conditional counting with CASE

Put a CASE inside SUM to count only some rows per group.

25. Join first, then aggregate

LEFT JOIN keeps Marketing, and COUNT(u.id) correctly reports 0 because it ignores the NULL side.

Navigation

LivePreparation

Client-side workspace · saved locally