Skip to content
Visual explainer 3h to learn 4 steps

GROUP BY, HAVING & aggregates

Summarise data by group and filter on aggregate results.

By Invicly Tech, , in SQL & PostgreSQL. About 8 minutes to read.

Topic 6 of 30

In short

Aggregates such as COUNT, SUM and AVG collapse many rows into one value. GROUP BY makes one result row per group, and HAVING filters those groups after the aggregates are computed.

Explained simply

Most business questions are about totals, not single rows. How many orders came in today? What is the revenue per country? Which product sells best? Aggregate functions answer these by squeezing many rows into one number.

GROUP BY decides how the rows are split before squeezing. Picture sorting a pile of receipts into one stack per shop. Then you add up each stack. GROUP BY shop makes the stacks, and SUM(amount) adds up each one.

After grouping, each result row stands for a whole stack, not one receipt. That is why you can only show columns that are the same for the whole stack (the grouping columns) or a summary of it (an aggregate).

HAVING is a filter for stacks. WHERE throws away single receipts before stacking. HAVING throws away whole stacks after they are added up, like "only shops where we spent more than 100".

Press Play on a diagram to walk through it one step at a time.

FlowQuery execution order
  1. 1
    FROM / JOIN

    Build the combined set of rows

  2. 2
    WHERE

    Filter individual rows

  3. 3
    GROUP BY

    Bucket rows sharing the same key

  4. 4
    HAVING

    Filter whole groups by aggregate values

  5. 5
    SELECT

    Compute output columns and aggregates

  6. 6
    ORDER BY

    Sort the final rows

  7. 7
    LIMIT

    Keep the first N

CompareWHERE vs HAVING on the same table
WHERE status = 'paid'
  • Runs before grouping
  • Looks at one row at a time
  • Cannot use SUM, COUNT, AVG
  • Makes grouping cheaper
HAVING SUM(total) > 500
  • Runs after grouping
  • Looks at one whole group
  • Usually uses an aggregate
  • Removes groups, not rows

In depth

How Postgres builds the groups

Postgres has two main ways to group. HashAggregate reads every row once and keeps a small in-memory table with one entry per group, updating the running count or sum as it goes. It is fast when the number of groups fits in memory. GroupAggregate first sorts the rows by the grouping columns, then walks through them and closes a group each time the key changes. It is used when the data is already sorted, for example from an index, or when there are too many groups for memory.

Either way, the output order is not guaranteed. Always add ORDER BY if you care about the order of groups.

CompareTwo ways Postgres groups rows
HashAggregate
  • Reads every row once
  • In-memory table, one entry per group
  • Fast when groups fit in memory
GroupAggregate
  • Sorts by the grouping columns first
  • Closes a group when the key changes
  • Used for sorted input or many groups

Choosing the right aggregate

COUNT(*) counts rows. COUNT(col) skips NULLs. COUNT(DISTINCT col) counts unique values. SUM, AVG, MIN and MAX work on numbers, and MIN and MAX also work on text and dates.

Postgres adds some very useful ones. string_agg(name, ', ' ORDER BY name) joins values into one text. array_agg(id) collects them into an array. bool_or(paid) is true if any row is true. percentile_cont(0.5) WITHIN GROUP (ORDER BY price) gives the median, which is often more honest than the average when a few huge values exist.

  • COUNT(DISTINCT customer_id): unique buyers
  • string_agg: comma-separated list per group
  • percentile_cont(0.5): the median
  • FILTER (WHERE ...): aggregate only some rows

The functional dependency shortcut

Normally every non-aggregated column must appear in GROUP BY. Postgres relaxes this in one safe case: if you group by a table's primary key, you may select any other column of that same table. Grouping by customers.id means name and email are already fixed for each group, so Postgres lets you select them.

This keeps queries shorter: GROUP BY c.id instead of GROUP BY c.id, c.name, c.email, c.country. It only works for the primary key, not for a column that merely happens to be unique.

Subtotals with ROLLUP and GROUPING SETS

Reports often want totals at several levels: per country and city, per country, and a grand total. Instead of three queries glued with UNION ALL, write GROUP BY ROLLUP (country, city). Postgres returns the city rows, a subtotal row per country with city as NULL, and a grand total row with both NULL.

GROUPING SETS lets you list exactly which combinations you want, and CUBE gives every combination. The GROUPING(city) function returns 1 on subtotal rows, so you can label them "All cities" instead of showing NULL.

MapRows from GROUP BY ROLLUP (country, city)
ROLLUP (country, city)
  • (country, city)
    • One row per city
  • (country)
    • Subtotal per country
    • city is NULL
  • ()
    • Grand total
    • Both columns NULL

Learn it in 4 short steps

About 45m each. Track them with a timer in your plan.

  1. 1
    Use COUNT, SUM, AVG, MIN, MAX~45m
  2. 2
    Group rows with GROUP BY~45m
  3. 3
    Filter groups with HAVING~45m
  4. 4
    Avoid common grouping mistakes~45m

Key points

  • Every selected column must be in GROUP BY or inside an aggregate.
  • WHERE filters rows before grouping; HAVING filters groups after.
  • COUNT(*) counts rows; COUNT(col) counts non-NULL values.
  • COUNT(DISTINCT col) counts unique values per group.

Key terms

Tap a card to flip it. 0/4 known

Examples

sql
SELECT
  customer_id,
  COUNT(*)            AS orders,
  SUM(total)          AS revenue,
  ROUND(AVG(total), 2) AS avg_order
FROM orders
WHERE status = 'paid'
GROUP BY customer_id
HAVING SUM(total) > 500
ORDER BY revenue DESC
LIMIT 10;

Revenue per country, with only real markets

Finance wants paid revenue per country, but only countries with at least 20 orders. Step 1: WHERE keeps paid orders only, before grouping. Step 2: join customers to get the country. Step 3: GROUP BY country. Step 4: compute count, sum and average. Step 5: HAVING drops small countries using the count. Step 6: sort by revenue.

sql
SELECT c.country,
       COUNT(*)              AS orders,
       SUM(o.total)          AS revenue,
       round(AVG(o.total), 2) AS avg_order
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.status = 'paid'
GROUP BY c.country
HAVING COUNT(*) >= 20
ORDER BY revenue DESC;

Tracing a grouping by hand

Take 5 orders: (Ann, 10), (Ann, 30), (Bob, 5), (Cy, 50), (Cy, NULL). GROUP BY customer makes three stacks. Ann: COUNT(*) 2, SUM 40, AVG 20. Bob: COUNT(*) 1, SUM 5. Cy: COUNT(*) 2 but COUNT(total) 1, SUM 50 and AVG 50, because the NULL is ignored. HAVING SUM(total) > 20 keeps Ann and Cy. Doing this once on paper makes the rules stick.

Quick reference

  • Every SELECT column is either in GROUP BY or inside an aggregate
  • WHERE filters rows before grouping; HAVING filters groups after
  • GROUP BY table.id lets you select any other column of that table
  • COUNT(*) FILTER (WHERE status = 'refunded') counts only some rows
  • string_agg(name, ', ' ORDER BY name) makes a list per group
  • GROUP BY ROLLUP (a, b) adds subtotals and a grand total
  • Groups come back unordered unless you add ORDER BY

Common mistakes

  • Putting an aggregate condition in WHERE, which is an error.
  • Selecting a column that is neither grouped nor aggregated.
  • Summing after a one-to-many join and counting values twice.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Why does SELECT country, city, COUNT(*) FROM customers GROUP BY country; fail?

Question 2

2Where should a condition like status = 'paid' go when you sum revenue per customer?

Question 3

3What does GROUP BY ROLLUP (country, city) add compared to GROUP BY country, city?

Question 4

4Which expression gives the median order total?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    From products(category, price), show each category with its number of products and its cheapest price.

  2. Exercise 2medium

    From orders(customer_id, total, status), find customers who placed at least 3 orders but have never had one refunded.

  3. Exercise 3hard

    Show revenue per year and month for paid orders, with a subtotal per year and a grand total, labelling subtotal rows clearly.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Can I use a SELECT alias in GROUP BY?
Yes, Postgres allows GROUP BY alias and also GROUP BY 1 to mean the first output column. HAVING, however, needs the full expression.
Is SELECT DISTINCT the same as GROUP BY?
For simply removing duplicates they give the same rows. Use GROUP BY when you also want aggregates per group.
Why does SUM return NULL instead of 0?
When there are no rows, or all values are NULL, SUM has nothing to add and returns NULL. Wrap it in COALESCE(SUM(x), 0) if you want 0.

Go deeper

ShareXLinkedInWhatsApp