Interview's MateData Science
Interview's Mate

Data Science

Python → ML → MLOps

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
Data Science topics
Lesson 23/ 160
02. SQL & Data Engineering Basics

Aggregate Functions & GROUP BY / HAVING

Compute COUNT/SUM/AVG metrics, group rows, and filter groups with HAVING.

BeginnerAggregates · GROUP BY3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Missing counts in one query

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.

Key takeaway: Every selected column is grouped or aggregated; know how NULLs behave.

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.

Refund rate by category

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.

Key takeaway: WHERE for rows, HAVING for groups; conditional aggregates for rates; reconcile totals.

How it works, step by step

Step 1 of 4
Design

1. Define the output grain

Decide what one output row means (customer, customer-month) and which columns are the group keys.

GROUP BY customer_id
Key numbers at this step
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

SQL GROUP BY in the warehouse
Best for: Large data and feature tables

Strengths: Scales; returns small results.

Watch out: Less interactive; dialect details.

pandas groupby
Best for: Data already in memory and exploration

Strengths: Flexible; rich Python functions.

Watch out: Memory-bound; needs raw rows downloaded.

Materialised summary tables
Best for: Repeated dashboards and features

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?
Interview tip: Always say you'd reconcile the aggregate against a raw total. It's the cheapest way to catch fan-out and filter mistakes.

Knowledge check

Loading quiz

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.

Open Data Science Q&A →Machine Learning Q&A
Previous topic
SELECT, WHERE, ORDER BY & Filtering
Next topic
INNER, LEFT, RIGHT & FULL Joins