Skip to content
Tech Interview Prep
Technical interview guide

Aggregations & GROUP BY

Collapsing many rows into one summary row per group (counts, sums, and averages) plus the HAVING clause that filters groups.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v4
Editorial status
Reviewed

Scope: SQL principles with PostgreSQL 18 examples; vendor-specific behavior must be verified.

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

AVG(x)=∑xi#{xi≠NULL}\text{AVG}(x)=\frac{\sum x_i}{\#\{x_i \neq \text{NULL}\}}

Quiz example (labelled hypothetical, scores 80, 90, NULL, 70, NULL, 100): 80+90+70+1004=8580+90+70+1006≈56.7\frac{80+90+70+100}{4}=85 \qquad \frac{80+90+70+100}{6}\approx 56.7 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

FROM and JOIN WHERE row filter GROUP BY one bucket per key HAVING group filter SELECT aggregates and windows ORDER BY and LIMIT
  • 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

SituationUseAvoid
Totals per keyGROUP BY with aggregatesWindow functions, which keep every row
Each row shown with its group totalWindow functionGROUP BY, which collapses rows
Several filtered metrics in one passFILTER clause or CASESeveral queries or self-joins
Subtotals and grand totalROLLUP or CUBEUNION ALL of near-identical queries
Top N per groupWindow in a subquery, filtered outsideFiltering the window in WHERE
Slowly changing data read repeatedlyRollup table or materialized viewRecomputing the scan per request

Traps interviewers probe

  1. Aggregate in WHERE. It fails because no groups exist yet during WHERE. Fix: move the test to HAVING. Move non-aggregate predicates to WHERE.
  2. 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.
  3. 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.
  4. Empty SUM returning NULL. Fix: COALESCE(SUM(amount), 0) when the report needs zero.
  5. 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:

  1. Define it: one row per group, aggregates over the group.
  2. Order of evaluation: WHERE, GROUP BY, HAVING, SELECT.
  3. NULL rules: COUNT(*) vs COUNT(col), SUM of nothing is NULL.
  4. The grain risk: check the row count before and after each join.
  5. 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.