Skip to content
Commitwise
Menu
Databases

Aggregation: GROUP BY and HAVING

count, sum, avg, min and max, why count(column) and count(*) differ, one row per group with GROUP BY, the months that vanish from a sales report, WHERE vs HAVING, and finding duplicates and customers who bought every product. Reporting SQL for interviews and real dashboards.

beginner

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

“How many orders did we get yesterday?” “Revenue per month?” “Which customers ordered more than five times?” Most questions a business asks of its data are about groups of rows, not single rows. The answer is aggregation: collapse many rows into one number, or into one row per group.

It’s also where SQL interviews start getting interesting. A conversion rate that’s always 0, a report missing the month with no sales, an average that ignores half the customers: all of these are aggregation bugs. The examples use the shop tables from How relational databases work.

New to some of these? Open what you need, or skip ahead.

Basics:SELECT, WHERE and NULL

SELECT columns FROM table WHERE condition ORDER BY column reads rows; it runs FROM, then WHERE, then SELECT, then ORDER BY. NULL means “no value”: a comparison with it is unknown, so you test it with IS NULL. The SQL basics lesson covers both.

Basics:JOIN

A join puts rows from two tables side by side, matching them with ON, usually foreign key = primary key: FROM orders o JOIN customers c ON c.id = o.customer_id. An inner join returns one row per match. See Joins.

Part Not started

Counting and summing: aggregate functions

An aggregate functionAggregate functionA SQL function that turns many rows into one value: count, sum, avg, min, max.Open in glossary → takes a whole column of values and returns one:

SELECT count(*)   AS orders,
       sum(total) AS revenue,
       avg(total) AS average_order,
       min(total) AS smallest,
       max(total) AS largest
FROM orders
WHERE created_at >= date '2026-11-01';

However many orders match, the result is one row.

count comes in three forms, and the difference matters:

You writeIt counts
count(*)rows
count(country)rows where country is not NULL
count(DISTINCT country)different non-NULL countries

All the others (sum, avg, min, max) also skip NULLs. And if no rows match at all, count(*) is 0 but sum(total) is NULL, not 0. Write COALESCE(sum(total), 0) when you need a number.

One more surprise: dividing two whole numbers gives a whole number in PostgreSQL, SQLite and SQL Server. 7 / 2 is 3, and 1 / 4 is 0. When you divide counts, turn one side into a decimal first: 7 * 1.0 / 2 or 7::numeric / 2.

  • count(*) vs count(1): identical in every major database. count(col) skips NULLs, count(DISTINCT col) needs a sort or hash of all values (expensive on big sets; approximate alternatives: HyperLogLog extensions, BigQuery APPROX_COUNT_DISTINCT).
  • NULL rules: aggregates ignore NULLs; avg divides by the non-NULL count; any aggregate except count returns NULL over zero rows.
  • Types: PostgreSQL avg(integer) returns numeric, but int / int truncates; SQL Server’s avg(int) returns an int. MySQL’s / always returns a decimal (DIV truncates).
  • Conditional aggregation: count(*) FILTER (WHERE status = 'PAID') (PostgreSQL, SQLite 3.30+) or the portable sum(CASE WHEN status = 'PAID' THEN 1 ELSE 0 END). One scan computes many metrics, the basis of pivot-style reports.
  • More aggregates: string_agg/array_agg (MySQL group_concat), bool_and/bool_or, percentile_cont(0.95) WITHIN GROUP (ORDER BY ms) for medians and p95 (an ordered-set aggregate), jsonb_agg for API payloads.
  • min/max on an indexed column can read one end of the index instead of the table.

Predict the output

customers has five rows with countries 'RS', 'RS', 'DE', NULL and NULL. What does this return?

SELECT count(*), count(country), count(DISTINCT country)
FROM customers;
SELECT count(*)                                       AS orders,
       count(*) FILTER (WHERE status = 'PAID')        AS paid,
       count(*) FILTER (WHERE status = 'CANCELLED')   AS cancelled,
       COALESCE(sum(total) FILTER (WHERE status = 'PAID'), 0) AS revenue,
       round(avg(total), 2)                           AS average_order
FROM orders
WHERE created_at >= date '2026-11-01';

-- the same counts without FILTER (works everywhere)
SELECT sum(CASE WHEN status = 'PAID' THEN 1 ELSE 0 END) AS paid
FROM orders;

The conversion rate that’s always zero

Spot the bugShare of carts that became orders

Tap the line with the bug.

-- carts: id, customer_id, created_at, ordered (boolean)
SELECT count(*) FILTER (WHERE ordered) / count(*) AS conversion
FROM carts
WHERE created_at >= date '2026-11-01';

Deep diveWhy count(*) is slow on a big PostgreSQL tableInterview favorite

“SELECT count(*) FROM events takes 40 seconds; MySQL’s MyISAM answered instantly.” Because of MVCCMVCCMulti-version concurrency control: writers create new row versions so readers never wait for them.Open in glossary →, PostgreSQL has no single row count: different transactions see different sets of rows, so every count must check each row’s visibility. The fastest it can do is an index-only scan of the smallest index, which still reads every entry and needs the visibility map to be up to date (recent VACUUM). InnoDB has the same problem; only MyISAM, without transactions, kept an exact counter.

Options, from exact to cheap:

  • count(*) = count(1); count(col) skips NULLs; count(DISTINCT) is costly. Aggregates skip NULLs; sum of nothing is NULL.
  • Integer division truncates in PostgreSQL, SQLite, SQL Server: 100.0 * a / NULLIF(b, 0).
  • Conditional aggregates: FILTER (WHERE …) or sum(CASE …); percentile_cont for medians and p95.
  • Exact count(*) on huge MVCC tables is slow: counters, reltuples estimates, or no total.
SELECT count(*) FILTER (WHERE status = 'PAID') AS paid,
       round(100.0 * count(*) FILTER (WHERE status = 'PAID') / NULLIF(count(*), 0), 1) AS paid_pct,
       percentile_cont(0.5) WITHIN GROUP (ORDER BY total) AS median_total
FROM orders;

Check this part

  1. What does count(email) count?

  2. No order matches the WHERE. What does sum(total) return?

  3. In PostgreSQL, what is SELECT 3 / 4?

  4. Why is an exact count(*) of a 500-million-row PostgreSQL table slow?

Aggregate functions turn many rows into one value: count(*) counts rows, count(col) counts non-NULL values, count(DISTINCT col) counts different values; sum, avg, min and max skip NULLs, and sum of no rows is NULL. Integer division truncates. FILTER or CASE gives conditional counts in one pass.

Part Not started

GROUP BY: one row per group

Without GROUP BY, an aggregate returns one row for the whole table. With it, you get one row per group:

SELECT country, count(*) AS customers
FROM customers
GROUP BY country
ORDER BY customers DESC;
countrycustomers
RS1840
DE920
NULL310

Think of sorting cards into piles by country, then counting each pile. Customers with no country end up in one pile together, shown as NULL.

The rule that causes most errors: every column in SELECT must either be in GROUP BY or be inside an aggregate. In a pile of 1,840 Serbian customers there’s one country, but 1,840 names. Which name should SELECT country, name, count(*) show? The database can’t choose, so it refuses with “column must appear in the GROUP BY clause or be used in an aggregate function”.

You can group by several columns, or by a calculated value. Revenue per month:

SELECT date_trunc('month', created_at) AS month,
       count(*)   AS orders,
       sum(total) AS revenue
FROM orders
WHERE status = 'PAID'
GROUP BY month
ORDER BY month;

date_trunc('month', …) cuts a timestamp down to the first moment of its month, so all November orders share the same value and fall into one group.

  • Grouping rules: the SQL standard allows selecting columns functionally dependent on the grouped key. PostgreSQL implements this for primary keys (GROUP BY c.id lets you select c.name); MySQL 5.7+ enforces ONLY_FULL_GROUP_BY with the same dependency detection, while older MySQL silently picked an arbitrary row’s value. SQLite still allows bare columns (and with a single min/max, takes them from that row).
  • NULLs group together, unlike in comparisons.
  • Missing groups: GROUP BY can only produce groups for rows that exist. A month with no sales simply isn’t there, and a chart connecting the points hides it. Generate the full series and left join (below).
  • Time zones: date_trunc('day', timestamptz) uses the session’s TimeZone; servers usually run in UTC, so a Belgrade order at 00:30 local time is counted on the previous day. Use date_trunc('day', created_at AT TIME ZONE 'Europe/Belgrade') or date_trunc('day', created_at, 'Europe/Belgrade') (PostgreSQL 12+).
  • Subtotals: GROUP BY ROLLUP (country, city) adds per-country and grand totals; CUBE adds every combination; GROUPING SETS lists exactly which. GROUPING(col) tells a subtotal’s NULL apart from a real NULL.
  • Execution: HashAggregate (hash table of groups, needs memory; spills to disk since PostgreSQL 13) or GroupAggregate over sorted input, which an index on the grouping columns can provide.

Predict the output

customers has five rows with countries 'RS', 'RS', 'DE', NULL and NULL. How many rows does this return?

SELECT country, count(*)
FROM customers
GROUP BY country;
-- orders and revenue per customer, with the customer's name
SELECT c.id, c.name, count(o.id) AS orders, COALESCE(sum(o.total), 0) AS spent
FROM customers c
LEFT JOIN orders o ON o.customer_id = c.id AND o.status = 'PAID'
GROUP BY c.id, c.name
ORDER BY spent DESC
LIMIT 10;

-- units sold per product and month
SELECT p.name,
       date_trunc('month', o.created_at) AS month,
       sum(oi.quantity) AS units
FROM order_items oi
JOIN orders o   ON o.id = oi.order_id
JOIN products p ON p.id = oi.product_id
GROUP BY p.name, month
ORDER BY month, units DESC;

Worked example: grouping, step by step

Six paid orders:

idcreated_attotal
12026-09-0320
22026-09-1835
32026-10-0210
42026-10-0215
52026-10-2940
62026-11-0525

Now run the “revenue per month” query from above.

  1. FROM orders WHERE status = 'PAID': all six rows.
  2. Compute the group key. date_trunc('month', created_at) turns each date into the first of its month: rows 1 and 2 get September 1, rows 3, 4 and 5 get October 1, row 6 gets November 1.
  3. Make piles. Three groups: September (2 rows), October (3 rows), November (1 row).
  4. Aggregate each pile. September: count 2, sum 55. October: count 3, sum 65. November: count 1, sum 25.
  5. ORDER BY month: September, October, November. Three rows out, six rows in.
Deep diveThe month with no sales is missingInterview favorite

A store closed for August. The revenue chart goes straight from July to September, and the year-over-year comparison is off by a month because the code assumed twelve rows. GROUP BY can’t produce a group for rows that don’t exist.

Generate every month first, then left join the data to it:

WITH months AS (
    SELECT generate_series(date '2026-01-01', date '2026-12-01', interval '1 month') AS month
)
SELECT m.month,
       count(o.id)                AS orders,
       COALESCE(sum(o.total), 0)  AS revenue
FROM months m
LEFT JOIN orders o
       ON o.status = 'PAID'
      AND o.created_at >= m.month
      AND o.created_at <  m.month + interval '1 month'
GROUP BY m.month
ORDER BY m.month;

Three details interviewers look for: count(o.id) instead of count(*) (the empty month’s NULL row would count as 1); the status filter in ON, not WHERE (from the Joins lesson); and a range on created_at instead of date_trunc(…) = m.month, so an index on created_at can be used. For time zones, generate the series in local time and convert: m.month AT TIME ZONE 'Europe/Belgrade'. Without generate_series (MySQL before 8, SQLite), use a recursive CTE or a permanent calendar table, which data warehouses keep anyway for holidays and fiscal periods.

  • Every selected column: grouped, aggregated, or functionally dependent on a grouped primary key (PostgreSQL, MySQL ONLY_FULL_GROUP_BY).
  • NULLs form one group. Empty groups don’t exist: generate_series or a calendar table + LEFT JOIN + count(o.id).
  • Group timestamps in the business time zone (AT TIME ZONE), filter with ranges for index use.
  • ROLLUP/CUBE/GROUPING SETS for subtotals; HashAggregate vs GroupAggregate.

Check this part

  1. SELECT country, name, count(*) FROM customers GROUP BY country fails. Why?

  2. How many groups does GROUP BY country make for countries RS, RS, DE, NULL, NULL?

  3. A daily revenue report must show days with zero sales. What do you do?

  4. Servers run in UTC; the business is in Belgrade. What goes wrong with date_trunc('day', created_at)?

GROUP BY returns one row per group, and every selected column must be grouped or aggregated. NULLs form one group. Groups with no rows don't appear: generate the full list of months or days and LEFT JOIN the data. Group dates in the business time zone.

Part Not started

HAVING: filtering groups

“Customers with more than five orders” needs a condition on count(*). You can’t put it in WHERE: WHERE runs on single rows, before the groups exist, so there’s no count yet.

That’s what HAVING is for. It filters groups, after they’re counted:

SELECT customer_id, count(*) AS orders
FROM orders
WHERE status = 'PAID'          -- 1. keep paid orders (rows)
GROUP BY customer_id           -- 2. one pile per customer
HAVING count(*) > 5            -- 3. keep piles with more than 5
ORDER BY orders DESC;

The full order SQL runs in:

  1. FROM and JOIN
  2. WHERE: filter rows
  3. GROUP BY: make groups
  4. HAVING: filter groups
  5. SELECT: compute columns
  6. ORDER BY, then LIMIT

A simple rule: conditions on single rows go in WHERE, conditions on aggregates (count, sum, avg…) go in HAVING.

HAVING is also how you find duplicates. Emails used by more than one customer:

SELECT lower(email) AS email, count(*)
FROM customers
GROUP BY lower(email)
HAVING count(*) > 1;
  • Placement: non-aggregate predicates belong in WHERE, which filters before grouping and can use indexes. PostgreSQL moves a HAVING predicate on a grouping column down to WHERE itself, but don’t rely on it for readability or across databases.
  • Conditional HAVING answers “customers who did X but never Y” in one pass: HAVING bool_or(p.category = 'coffee') AND NOT bool_or(p.category = 'mugs'), or with sum(CASE …) counts.
  • Relational division (“customers who bought every product in a category”): count distinct matches per customer and compare with the total (below).
  • Duplicates: GROUP BY the identifying columns HAVING count(*) > 1 shows which; deleting them uses row_number() (the Window functions lesson) or DELETE … USING with a.id > b.id.
  • Top-N groups: ORDER BY sum(total) DESC LIMIT 10 works with grouping; “top N within each group” doesn’t, and needs window functions.
  • Joins before grouping multiply rows, so HAVING count(*) > 5 after joining items counts items, not orders. Count DISTINCT o.id, or aggregate before the join.

Predict the output

Ana has three orders, but only one is PAID. Is she in the result?

SELECT customer_id, count(*)
FROM orders
WHERE status = 'PAID'
GROUP BY customer_id
HAVING count(*) >= 2;
-- products that sold more than 100 units in October, best first
SELECT p.id, p.name, sum(oi.quantity) AS units
FROM order_items oi
JOIN orders o   ON o.id = oi.order_id
JOIN products p ON p.id = oi.product_id
WHERE o.status = 'PAID'
  AND o.created_at >= date '2026-10-01'
  AND o.created_at <  date '2026-11-01'
GROUP BY p.id, p.name
HAVING sum(oi.quantity) > 100
ORDER BY units DESC;

Practice: two reports

Exerciseeasy

Big spenders and best sellers

  1. List customers (id and name) whose paid orders add up to more than 1,000, with that total, biggest first.
  2. List the three products with the highest revenue (quantity * unit_price) across all paid orders.
›

Both need a join: customers to orders for the first, order items to orders (for the status) and products for the second.

›

“Paid” is a condition on single rows: WHERE. “More than 1,000 in total” is a condition on a sum: HAVING.

SolutionTry it yourself first
-- 1
SELECT c.id, c.name, sum(o.total) AS spent
FROM customers c
JOIN orders o ON o.customer_id = c.id
WHERE o.status = 'PAID'
GROUP BY c.id, c.name
HAVING sum(o.total) > 1000
ORDER BY spent DESC;

-- 2
SELECT p.id, p.name, sum(oi.quantity * oi.unit_price) AS revenue
FROM order_items oi
JOIN orders o   ON o.id = oi.order_id
JOIN products p ON p.id = oi.product_id
WHERE o.status = 'PAID'
GROUP BY p.id, p.name
ORDER BY revenue DESC
LIMIT 3;

The second one needs no HAVING: “top three” is sorting and LIMIT, applied after grouping.

Deep diveRelational division: customers who bought every product in a categoryInterview favorite

“Find customers who have bought all coffee products” can’t be answered by a join alone, which finds customers who bought any. The trick is counting: a customer qualifies when the number of different coffee products they bought equals the number of coffee products.

SELECT o.customer_id
FROM orders o
JOIN order_items oi ON oi.order_id = o.id
JOIN products p     ON p.id = oi.product_id
WHERE p.category = 'coffee'
  AND o.status = 'PAID'
GROUP BY o.customer_id
HAVING count(DISTINCT p.id) = (SELECT count(*) FROM products WHERE category = 'coffee');

DISTINCT matters: someone who bought the same espresso five times would otherwise reach the total without buying the rest.

The other classic formulation is a double negation: “customers for whom there is no coffee product they haven’t bought”:

SELECT c.id
FROM customers c
WHERE NOT EXISTS (
    SELECT 1 FROM products p
    WHERE p.category = 'coffee'
      AND NOT EXISTS (
          SELECT 1 FROM orders o JOIN order_items oi ON oi.order_id = o.id
          WHERE o.customer_id = c.id AND oi.product_id = p.id AND o.status = 'PAID'));

Edge cases to mention: if the category is empty, the NOT EXISTS version returns every customer (vacuously true) while the counting version returns none; decide which the business means. Discontinued products in the category change the answer, so filter on is_active consistently on both sides.

  • WHERE filters rows before grouping (indexes apply); HAVING filters groups by aggregates.
  • Duplicates: GROUP BY key HAVING count(*) > 1. “Did X, never Y”: HAVING bool_or(…) AND NOT bool_or(…).
  • Relational division: HAVING count(DISTINCT x) = (SELECT count(*) …), or double NOT EXISTS (differs on empty sets).
  • Joins before grouping multiply rows: count(DISTINCT o.id) or aggregate first.

Check this part

  1. Where does the condition count(*) > 5 go?

  2. Which runs first?

  3. How do you find customers who bought every product in a category?

  4. Orders joined to order_items, GROUP BY customer, HAVING count(*) > 5. What does it count?

WHERE filters rows before grouping; HAVING filters groups after, so aggregate conditions go in HAVING and everything else in WHERE. HAVING count(*) > 1 finds duplicates; counting distinct matches against a total solves 'bought every product' (relational division).

Key takeaways

  • count(*) counts rows, count(col) non-NULL values, count(DISTINCT col) different values. Other aggregates skip NULLs; sum of nothing is NULL.
  • Whole number ÷ whole number gives a whole number: use 100.0 * a / b.
  • GROUP BY gives one row per group; every selected column is grouped or aggregated. NULLs form one group.
  • WHERE filters rows before grouping, HAVING filters groups after.
  • HAVING count(*) > 1 finds duplicates.
  • Conditional aggregation with FILTER or CASE; percentile_cont for medians; exact counts on huge MVCC tables are expensive.
  • Functional dependency on grouped primary keys; ROLLUP/GROUPING SETS for subtotals.
  • Empty periods need a generated series or calendar table; group in the business time zone.
  • Relational division by counting or double NOT EXISTS; watch join fan-out before aggregates.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.