Aggregation without surprises
Part of the free LogicWiz Data Engineering course, Module 2: SQL for pipelines. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is 10:30 on Monday. Tess has three dashboards open, and each one answers the same question: how many customers does SwiftKart have? The first says 30, the second 29, the third 27. All three used COUNT, and none of them is broken.
You'll learn to
- Say what COUNT(*), COUNT(col) and COUNT(DISTINCT col) each count
- Name the grain of a GROUP BY before you write it
- Choose WHERE or HAVING for a filter
- Turn rows into columns with FILTER or CASE
Learn
Three counts, all of them right
Each dashboard counted something different, and nobody wrote down what.
COUNT(*)counts rows, whatever is in them.COUNT(email)counts the rows whereemailhas a value. It skips NULL.COUNT(DISTINCT email)counts the different emails. It skips NULL too.
SwiftKart has 30 customer rows. One has no email, so 29 have one. Three sign-ups share the same email, so there are 27 different emails.
Every number is right. The mistake is the label: all three dashboards say "customers". A good metric says which count it means.
Thirty customer rows, counted three ways
A bar of 30 customer rows split into 26 rows with their own email, 3 rows sharing one email and 1 row with no email, with brackets for COUNT star and COUNT email.
Read the brackets: COUNT(*) covers all three blocks, COUNT(email) skips the grey one. COUNT(DISTINCT email) takes 26 from the blue block and 1 from the amber one: 27.
All three at once
SELECT COUNT(*) AS customer_rows,
COUNT(email) AS with_email,
COUNT(DISTINCT email) AS distinct_emails
FROM customers;
Put the counts side by side like this whenever you meet a new table. The gaps between them are where the surprises live.
The trap: COUNT(*) after a LEFT JOIN counts the empty match. A customer with no orders still comes out as one row, with NULLs on the right, so COUNT(*) gives them 1. Count a column from the right-hand table instead, such as COUNT(o.order_id): it skips the NULL and gives 0.
Remember: COUNT(*) counts rows, COUNT(col) skips NULLs, COUNT(DISTINCT col) counts different values. Write down which one a metric means.
One row per what?
Tess moves on to her next report: orders per day.
Before you write GROUP BY, finish this sentence: "one row per ___". One row per day? Per day and status? Per customer? That is the grain of your result, the same word as in Lesson 2.1. The GROUP BY list is that sentence written in SQL.
Every column in SELECT must either be in the GROUP BY list or sit inside an aggregate: a function that turns many rows into one value, such as COUNT, SUM or MAX.
A classic slip is grouping by order_ts, a timestamp, when you meant the date. You asked for one row per second, and you get one row per order.
One row per day and status
SELECT DATE(order_ts) AS order_date, status, COUNT(*) AS orders
FROM orders
GROUP BY DATE(order_ts), status
ORDER BY order_date, status;
The grain is (day, status). A day with no cancelled orders has no cancelled row at all: grouping only makes rows for combinations that exist.
Filter rows first, groups after
The next question: which customers have three or more orders, not counting cancelled ones?
That sentence holds two filters. "Not cancelled" is about one order: a single row. "Three or more" is about a customer's whole pile of orders: a group.
SQL has a keyword for each. WHERE filters rows, before any group exists. HAVING filters groups, after they are counted. The reason is the order a query runs in: FROM and joins, then WHERE, then GROUP BY, then HAVING, then SELECT, then ORDER BY.
An aggregate in WHERE is an error. A row condition in HAVING works, but it runs later than it needs to. Filter early.
Eighty orders shrink to twelve customers
The phases of a grouped query in order: 80 order rows, 71 after WHERE removes cancelled orders, 28 groups after GROUP BY, 12 groups after HAVING, and 12 rows out.
FROM. Postgres starts with every row of
orders: 80 rows.WHERE. Each row is checked on its own. The 9 cancelled orders drop out, and 71 rows are left. No groups exist yet, so there is no count to test.
GROUP BY. The 71 rows are put in piles, one pile per customer: 28 groups. Now every group has a count.
HAVING. Each group is checked. Only 12 customers have a count of 3 or more.
SELECT and ORDER BY. One row is written for each group that is left, then the rows are sorted: 12 rows come out.
Read it top to bottom: each press of Next step runs one more phase of the query below.
Both filters in one query
SELECT customer_id, COUNT(*) AS orders
FROM orders
WHERE status <> 'cancelled'
GROUP BY customer_id
HAVING COUNT(*) >= 3
ORDER BY orders DESC, customer_id;
WHERE removes the cancelled orders before counting. HAVING keeps the customers whose remaining count is at least 3. Twelve rows come back, with customer 13 on top: 6 orders.
DISTINCT is not a repair tool
One of the dashboards once "fixed" a doubled total with DISTINCT. Look at what that does.
SUM(DISTINCT amount) adds each different value once. Two customers who each paid $14.99 count as one $14.99. That is almost never what anyone means.
The same goes for SELECT DISTINCT thrown at a result that "has duplicates". If the copies came from a fan-out, DISTINCT hides the rows, but any sum you take next is still too high. And next month a row that really does repeat disappears too.
Find out why rows repeat. Then fix the join or the grain.
SUM against SUM(DISTINCT)
SELECT SUM(amount) AS revenue,
SUM(DISTINCT amount) AS distinct_amounts
FROM payments
WHERE status = 'captured';
Seventy captured payments, but only 63 different amounts (three payments are $14.99, for example). SUM(DISTINCT) quietly loses $435.52.
Turn statuses into columns
Tess wants her daily report wide: one row per day, with a column for each status. Turning row values into columns is called a pivot.
You write one aggregate per column, and each one counts only its own rows:
COUNT(*) FILTER (WHERE status = 'cancelled')works in Postgres, DuckDB and a few othersSUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END)works everywhere
The grain becomes one row per day. Every day gets every column, with 0 where nothing happened. That is easier to chart and to compare than the long form.
One row per day, one column per status
SELECT DATE(order_ts) AS order_date,
COUNT(*) AS orders,
COUNT(*) FILTER (WHERE status = 'delivered') AS delivered,
COUNT(*) FILTER (WHERE status = 'shipped') AS shipped,
COUNT(*) FILTER (WHERE status = 'cancelled') AS cancelled,
SUM(CASE WHEN status = 'returned' THEN 1 ELSE 0 END) AS returned
FROM orders
GROUP BY DATE(order_ts)
ORDER BY order_date;
Fourteen rows, one per day. Three of the status columns use FILTER and the last one uses CASE: both do the same job.
1 June, long and wide
| Long: one row per (day, status) | Wide: one row per day |
|---|---|
| 2025-06-01, cancelled, 2 | 2025-06-01: orders 6, delivered 1, shipped 2, cancelled 2, returned 1 |
| 2025-06-01, delivered, 1 | (one row) |
| 2025-06-01, returned, 1 | |
| 2025-06-01, shipped, 2 |
Same facts, different grain. The long form is better for storing and for grouping again. The wide form is better for a report.
The same pivot in DuckDB
import duckdb
rows = duckdb.sql("""
SELECT CAST(order_ts AS DATE) AS order_date,
COUNT(*) AS orders,
COUNT(*) FILTER (WHERE status = 'cancelled') AS cancelled
FROM 'data/orders.csv'
GROUP BY order_date
ORDER BY order_date
LIMIT 3
""").fetchall()
for order_date, orders, cancelled in rows:
print(order_date, orders, cancelled)
DuckDB understands FILTER too, and also has a PIVOT statement. Spark has groupBy(...).pivot("status"). The idea is the same everywhere.
Under the hood: tally sheet or piles
How does Postgres build the groups? Think of counting votes. You can keep a tally sheet with one line per candidate, and add a mark for each ballot as it comes. Or you can sort the ballots into piles first, then count one pile at a time.
Postgres has both, and EXPLAIN names the one it chose.
- HashAggregate is the tally sheet. It reads the rows once, in any order, and keeps one hash table entry per group with its running
COUNTorSUM. - GroupAggregate is the sorted piles. Its input must arrive sorted on the group key, from a Sort step or an index. It walks the rows and finishes a group each time the key changes, holding one group at a time.
Both ways, on SwiftKart's 80 orders
On the left a hash table with one entry per status and its running count; on the right a sort by day followed by a walk that emits one group whenever the day changes.
Left: five entries, one per status, each with a running count. Right: sort by day, then walk the rows and close a group whenever the day changes. The counts and sizes are what EXPLAIN ANALYZE prints for the two queries below.
Which one did Postgres pick?
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT status, COUNT(*)
FROM orders
GROUP BY status;
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT DATE(order_ts) AS order_date, COUNT(*)
FROM orders
GROUP BY DATE(order_ts)
ORDER BY order_date;
The first plan is a HashAggregate with Batches: 1 Memory Usage: 32kB. The second is a GroupAggregate over a Sort. The result had to be ordered by day anyway, so one sort served both the grouping and the ORDER BY.
When the tally sheet outgrows memory
Memory for a HashAggregate grows with the number of groups, not rows. 100 million events grouped by country cost almost nothing. Grouped by session id, the hash table is as big as the sessions.
The hash table may use work_mem x hash_mem_multiplier: 8 MB by default. Past that, Postgres spills: groups that do not fit are written to temporary files in partitions and finished in later passes. The plan then shows Batches above 1 and a Disk Usage.
A GroupAggregate never holds more than one group, but its Sort can spill instead: Sort Method: external merge Disk: 2088kB.
Either way the answer is still right. It is slower.
Squeeze the memory and watch it spill
-- 5,000 customers: 5,000 groups, in memory
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT customer_id, SUM(amount)
FROM big_orders
GROUP BY customer_id;
-- a quarter of a megabyte for hashing
SET hash_mem_multiplier = 1;
SET work_mem = '256kB';
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT customer_id, SUM(amount)
FROM big_orders
GROUP BY customer_id;
-- the other strategy, with the same memory
SET enable_hashagg = off;
EXPLAIN (ANALYZE, COSTS OFF, TIMING OFF, SUMMARY OFF, BUFFERS OFF)
SELECT customer_id, SUM(amount)
FROM big_orders
GROUP BY customer_id;
Three plans. First, 5,000 groups in memory. Then the same groups with a quarter of a megabyte: Batches: 9 and a Disk Usage. Then the other strategy, where the sort spills. SET changes a setting for this session only, the safe way to give one heavy query more memory. enable_hashagg = off is for learning: in production you fix the estimate or the memory, not the planner.
Where the 5,000 groups lived
Two bars on one scale: with the default memory the hash aggregate used 1,393 kB of memory; limited to 256 kB it used 269 kB of memory and 3,448 kB of temporary files in 9 batches.
Same groups, two memory budgets: blue is memory, amber is temporary files, 3,448 kB written and read back. When Disk Usage shows up on a query that runs every few minutes, give that query more work_mem, or group by fewer keys.
Numbers to remember
| What | Number or name | What it means |
|---|---|---|
| workmem x hashmemmultiplier | 4 MB x 2.0 = 8 MB by default | The memory a HashAggregate may use before it spills |
| Hash aggregates that spill | Since Postgres 13 | Before 13 the planner avoided a hash aggregate it expected to be too big, and one it misjudged used more memory than allowed |
| Batches: 9 Memory Usage: 269kB Disk Usage: 3448kB | 5,000 groups squeezed into 256 kB | Batches above 1 means groups went to temporary files |
| Sort Method: external merge Disk: 2088kB | The Sort under a GroupAggregate | The sort did not fit in workmem and used disk |
| HashAggregate output | In no useful order | GroupAggregate output is sorted, which is why GROUP BY day ... ORDER BY day often picks it |
| ndistinct | A column statistic (Lesson 2.8) | The planner estimates the number of groups from it, then costs both ways |
| maxparallelworkerspergather | 2 by default | On a server each worker builds a partial hash and a final step merges them. Spark does the same around a shuffle (Module 12) |
| FILTER (WHERE ...) | Postgres, DuckDB and a few others | SUM(CASE WHEN ... THEN 1 ELSE 0 END) works everywhere |
What changed at SwiftKart
The three dashboards get honest labels: 30 customer rows, 29 with an email, 27 different emails. Tess picks the one finance means, and the argument is over.
Your own reports change too. Each one now starts with a comment that says "one row per ...". Row filters sit in WHERE, group filters in HAVING, and nobody reaches for DISTINCT to make a number look right.
Next, merchandising asks for the two best-selling products in each category. GROUP BY cannot answer that: it squashes each category into one row. Lesson 2.3 brings the tool that keeps every row and still ranks them.
In one line
Say "one row per ..." before GROUP BY; WHERE filters rows and HAVING filters groups; COUNT(*) counts rows, COUNT(col) skips NULLs and COUNT(DISTINCT col) counts different values.
Interview corner
What is the difference between WHERE and HAVING?
WHERE filters individual rows before they are grouped, so it cannot use aggregates. HAVING filters groups after aggregation, so it is where conditions like COUNT(*) > 3 go. I filter rows in WHERE whenever I can, because less data reaches the grouping step.
What do COUNT(*), COUNT(col) and COUNT(DISTINCT col) return?
COUNT(*) counts rows. COUNT(col) counts rows where col is not NULL. COUNT(DISTINCT col) counts distinct non-NULL values. On a customers table with a missing email and duplicate sign-ups, they give three different numbers, so a metric definition must say which one it means.
How do you turn rows into columns in SQL?
Group by the row key and write one conditional aggregate per output column: COUNT(*) FILTER (WHERE status = 'shipped') in Postgres or DuckDB, or SUM(CASE WHEN status = 'shipped' THEN 1 ELSE 0 END), which works everywhere. Some engines also have a PIVOT keyword, and Spark has groupBy().pivot().
What is the difference between a hash aggregate and a sort aggregate, and when does each hurt?
A hash aggregate reads rows in any order and keeps one hash entry per group, so its memory grows with the number of groups; past work_mem x hash_mem_multiplier (8 MB by default) it spills batches to disk, which Postgres can do since version 13. A sort aggregate sorts on the group key and streams one group at a time, so it needs little memory for itself, but the sort of every input row spills instead (external merge). Low-cardinality keys favour hashing; an input already sorted by an index, or an ORDER BY on the same key, favours the sort. Spark does the same with a partial aggregate before the shuffle and a final one after it.