Aggregate Functions & GROUP BY / HAVING
Compute COUNT/SUM/AVG metrics, group rows, and filter groups with HAVING.
In plain words
Group rows into buckets, calculate something for each bucket, and optionally keep only the buckets that meet a condition.
Think of it like…
Counting votes: you sort ballots into piles by candidate (GROUP BY) and count each pile (aggregate). HAVING is a rule applied after counting, such as "only report candidates with at least 100 votes", whereas WHERE would have thrown away ballots before counting.
Where you’ve seen it
A feature table for a churn model needs, per customer, orders in the last 90 days, total spend, average order value and the number of distinct product categories bought. One SQL query with GROUP BY customer_id produces 1.2 million rows, each with those four features, in 20 seconds; the pandas equivalent on raw order lines would first need 90 million rows loaded. She keeps only customers with at least one order using HAVING COUNT(*) >= 1, and checks that SUM(total_spend) equals the raw SUM(amount) for the same period.
Words you’ll hear
- COUNT(*) vs COUNT(col)
- COUNT(*) counts rows; COUNT(col) counts non-NULL values of col.
- GROUP BY
- Splits rows into groups by the listed columns before aggregating.
- HAVING
- A filter on aggregated results, applied after GROUP BY.
- Conditional aggregate
- SUM(CASE WHEN … THEN … END) or FILTER (WHERE …) to compute subsets in one pass.
Visual diagram
Theory & deep dive
Aggregates, groups and pandas equivalents
SELECT customer_id, COUNT(*) AS orders, SUM(amount) AS spend, AVG(amount) AS aov, COUNT(DISTINCT category) AS categories FROM orders WHERE created_at >= :start GROUP BY customer_id is the SQL equivalent of df.groupby("customer_id").agg(orders=("order_id", "size"), spend=("amount", "sum"), ...). Every non-aggregated column in the SELECT must appear in GROUP BY. Group by the columns that define your output grain, and use GROUP BY 1, 2 ordinals only in quick exploration.
NULL behaviour: SUM, AVG, MIN and MAX ignore NULLs; COUNT(col) counts non-NULLs and COUNT(*) counts rows, so COUNT(*) - COUNT(col) is the number of missing values. SUM over no rows returns NULL, not 0, so wrap with COALESCE(SUM(x), 0). Averages of averages are wrong when groups differ in size: compute SUM(x) / SUM(n) from the underlying data.
SELECT COUNT(*) AS rows, COUNT(coupon) AS coupon_filled, COUNT(*) - COUNT(coupon) AS coupon_missing FROM orders; gives a quick profile of a column without leaving SQL.
HAVING, conditional aggregation and reconciliation
HAVING filters groups on aggregate values (HAVING COUNT(*) >= 5 AND AVG(rating) < 3), while WHERE filters rows before grouping, so put row-level conditions in WHERE (faster, since fewer rows are grouped). Conditional aggregation computes several subsets in one pass: SUM(CASE WHEN status = 'refunded' THEN amount ELSE 0 END) AS refunds or, in PostgreSQL and SQLite, COUNT(*) FILTER (WHERE status = 'paid'). These are the building blocks of rates (paid / total) and one-hot-style features.
Reconcile aggregates with a control total: SELECT SUM(spend) FROM feature_table should equal SELECT SUM(amount) FROM orders WHERE … for the same filters. Mismatches usually come from joins that duplicated rows, filters applied differently, or NULL keys dropped by GROUP BY or joins. When aggregating after joins, aggregate each many-side table to the key level first, then join, to avoid inflating sums.
SELECT category, SUM(CASE WHEN status = 'refunded' THEN 1 ELSE 0 END)::float / COUNT(*) AS refund_rate FROM orders GROUP BY category HAVING COUNT(*) >= 200 ORDER BY refund_rate DESC; The HAVING avoids noisy rates from tiny categories.
How it works, step by step
Step 1 of 41. Define the output grain
Decide what one output row means (customer, customer-month) and which columns are the group keys.
- Grain
- first
When to use it & trade-offs
What it is
Aggregate functions (COUNT, SUM, AVG, MIN, MAX, COUNT(DISTINCT …)) collapse many rows into one value; GROUP BY computes them per group; HAVING filters groups after aggregation (WHERE filters rows before). Together they produce the metrics and feature tables data scientists need: orders per customer, revenue per month, conversion per campaign. Doing the aggregation in SQL means pandas receives a small summary instead of millions of raw rows.
Why it matters: Warehouses aggregate billions of rows in seconds; pulling raw rows into pandas to do the same is slow or impossible. But aggregate mistakes are easy to make and hard to spot: COUNT(*) vs COUNT(column) ignoring NULLs, averaging averages, aggregating after a join that multiplied rows, and mixing WHERE and HAVING. A habit of reconciling totals prevents shipping wrong metrics.
When to reach for it
- Customer-level feature tables
- Metrics by period, segment and channel
- Quality profiles of columns
When to avoid or be careful
- Averaging averages across unequal groups
- Aggregating after a join that duplicated rows
- Assuming SUM of no rows is 0
Where to aggregate
Strengths: Scales; returns small results.
Watch out: Less interactive; dialect details.
Strengths: Flexible; rich Python functions.
Watch out: Memory-bound; needs raw rows downloaded.
Strengths: Fast reads; consistent definitions.
Watch out: Refresh jobs and staleness.
Interview signals & numbers to know
When this topic comes up
- “Compute features per customer”
- “WHERE vs HAVING”
- “COUNT(*) vs COUNT(column)”
- Conversion rates by segment
- Reconciling totals
Benchmarks & rules of thumb
- 90M → 1.2M
- rows before and after aggregation in the example
- COUNT(*) − COUNT(col)
- missing values in col
- 200
- a minimum group size for a stable rate in the example
Common mistakes & follow-ups
Common interview mistakes
- Selecting a non-grouped column and getting an error or an arbitrary value.
- Putting a row-level condition in HAVING, making the query slower than WHERE.
- Reporting category rates from groups of five orders.
Likely interviewer follow-ups
- What's the difference between WHERE and HAVING?
- How do aggregates treat NULLs?
- How do you build a rate such as refund percentage in SQL?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Aggregate Functions & GROUP BY / HAVING with data science interview Q&A and hands-on practice.