Overview
Curated: · Written: · Reviewed:
Aggregations & GROUP BY
In one line
An aggregate collapses many rows into one value per group (COUNT, SUM, AVG, MIN, MAX), and HAVING filters the groups after they form. Reach for it whenever the question asks for a total, count or average per key.
Key definitions
- Aggregate: reduces a set of input rows to one value. Ignores NULL inputs, except COUNT(*), which counts rows.
- Grain: what one row of a join or result represents. Aggregating above the true grain double-counts.
- WHERE vs HAVING: WHERE filters rows before grouping. HAVING filters groups after grouping.
- Conditional aggregation:
FILTER (WHERE ...)or CASE inside an aggregate, computing several filtered metrics in one scan. - Grouping sets: ROLLUP, CUBE and GROUPING SETS add subtotal levels. GROUPING() flags the rolled-up rows.
- Window function: computes over a partition without collapsing rows. It cannot appear in WHERE or HAVING.
Formulas and complexity
Quiz example (labelled hypothetical, scores 80, 90, NULL, 70, NULL, 100): The first is AVG, which skips the NULLs. The second is SUM/COUNT(*), which counts skipped rows. A hash aggregate uses working memory (work_mem). When the group count outgrows it, the aggregate spills to disk.
How it works
- Joins run before grouping, so a one-to-many join duplicates parent rows before SUM sees them.
- Predicates without an aggregate belong in WHERE, because they shrink the input before grouping.
- NULLs in the grouping column form one group, since grouping treats NULLs as equal.
- SUM over zero rows returns NULL. COUNT over zero rows returns 0.
- Hash aggregate builds a hash table of groups. Group aggregate sorts, then collapses runs. High cardinality can make the hash table spill.
When to use and when not to
| Situation | Use | Avoid |
|---|---|---|
| Totals per key | GROUP BY with aggregates | Window functions, which keep every row |
| Each row shown with its group total | Window function | GROUP BY, which collapses rows |
| Several filtered metrics in one pass | FILTER clause or CASE | Several queries or self-joins |
| Subtotals and grand total | ROLLUP or CUBE | UNION ALL of near-identical queries |
| Top N per group | Window in a subquery, filtered outside | Filtering the window in WHERE |
| Slowly changing data read repeatedly | Rollup table or materialized view | Recomputing the scan per request |
Traps interviewers probe
- Aggregate in WHERE. It fails because no groups exist yet during WHERE. Fix: move the test to HAVING. Move non-aggregate predicates to WHERE.
- Join fan-out inflating SUM. Fix: aggregate the child to one row per key first, or aggregate at the true grain. SELECT DISTINCT only hides the duplicates and fails when two real child rows match on every projected column.
- COUNT over a CASE with ELSE 0. COUNT counts zeros, so every row is counted. Fix: use ELSE NULL, or SUM(CASE WHEN ... THEN 1 ELSE 0 END), or FILTER.
- Empty SUM returning NULL. Fix: COALESCE(SUM(amount), 0) when the report needs zero.
- Averaging per-group averages. The mean of group means weights small groups as heavily as large ones. Fix: take the average of per-group sums in a subquery, or state which average you mean.
Interview tips
Open with the model: "It collapses rows to one per group. WHERE filters rows before grouping, HAVING filters groups after." Follow-ups to expect:
- Why can't COUNT appear in WHERE? (No groups exist yet.)
- COUNT(*) vs COUNT(col) vs COUNT(DISTINCT col) on a column with NULLs.
- Why did the total change after a join? (Fan-out at the wrong grain.)
- Top three per category. (Window with row_number in a subquery, filter outside.)
- Materialized view staleness. (Worst case is the refresh interval plus the refresh duration.)
- Why did the staging query fast and production slow? (Spill past work_mem, or a missing index.)
30-second outline:
- Define it: one row per group, aggregates over the group.
- Order of evaluation: WHERE, GROUP BY, HAVING, SELECT.
- NULL rules: COUNT(*) vs COUNT(col), SUM of nothing is NULL.
- The grain risk: check the row count before and after each join.
- One concrete example, then the trade-off: compute on demand or precompute with a stated staleness bound.
Feedback on this overview
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.