14 min read
SQL GROUP BY, HAVING and subqueries
In one sentence: An aggregate function, like COUNT or SUM, sums up many rows into a single value. GROUP BY makes that summary by groups (one per product, one per day) and HAVING keeps the groups you want. A subquery is a query inside another one: it lets you compare each row with a summary, or summarize a summary.
What you will learn
- Summarize a table with COUNT, SUM, AVG, MIN and MAX, and know what COUNT(*) counts and what COUNT(column) counts.
- Group with GROUP BY and filter the groups with HAVING, knowing when WHERE goes and when HAVING does.
- Explain the order a query runs in, and use it to understand PostgreSQL's errors.
- Use a subquery in WHERE and another in FROM.
Before you start, read: 02-join.md
The problem
Section titled “The problem”It’s Sunday and Ana wants the week’s report: how much each product has brought in, which was the best day and which orders were bigger than usual. With what you know from lessons 1 and 2, a SELECT gives her the 25 orders with their product, and she adds them up with a calculator.
With 25 orders, that’s doable. With 40,000, it isn’t. And doing the math on the shop’s ServerA program that waits for requests and answers them. By extension, the computer it runs on is also called a server.Go to definition doesn’t fix anything either: it would ask the DatabaseA program that stores data in an organized way and lets you search and change it quickly, even when many people use it at once. The backend keeps in it whatever needs to last.Go to definition for the 40,000 rows, which would travel over the network, just to keep three numbers.
What Ana needs is for the database to summarize: to do the math where the data is and return only the result, three rows instead of 40,000.
The analogy
Section titled “The analogy”The analogy
Think of the week’s box of receipts. To find out how much you’ve sold of each product, you first set aside the voided receipts. Then you sort the rest into piles, one per product, and add up each pile. At the end, maybe you throw out the small piles.
That’s the whole lesson: setting receipts aside is WHERE, making piles is GROUP BY, adding up each pile is SUM and throwing out piles is HAVING. And the order matters: you can’t throw out a pile for its total before you add it up.
Where the analogy breaks down
- You can look inside a pile. The database returns a single row per pile, so you can only ask for what’s the same across the whole pile, or a summary of it.
- The database doesn’t really make piles: it can sort the rows or keep a running count per group, whichever is faster. The result is the same.
How it really works
Section titled “How it really works”You can try each query in the playground in Try it or in psql. The outputs are from PostgreSQL 18.6, with the data from shop.sql freshly loaded.
An aggregate function sums up many rows into one
Section titled “An aggregate function sums up many rows into one”SELECT COUNT(*), SUM(quantity), MIN(quantity), MAX(quantity), AVG(quantity)FROM orders; count | sum | min | max | avg-------+-----+-----+-----+-------------------- 25 | 62 | 1 | 4 | 2.4800000000000000(1 row)A single row, even though orders has 25. Each of those five is an Aggregate functionAn SQL operation that sums up many rows of a table into a single value, such as how many there are (COUNT), what they add up to (SUM) or their average (AVG). If the rows are split into groups, for example one per product, it gives one value for each group.Go to definition: it takes all the rows and returns one value.
COUNT(*)counts rows: 25 orders.SUM(quantity)adds up the column: 62 units sold.MINandMAXgive the smallest and the largest value: nobody has ordered fewer than 1 or more than 4. They work with dates too:MAX(created_at)is the most recent order.AVG(quantity)gives the average: 2.48 units per order.
Look at the average: 2.4800000000000000. AVG returns a numeric, PostgreSQL’s type for exact decimals, and writes it with 16 decimal places. To show it, round it with round:
SELECT round(AVG(quantity), 2) AS averageFROM orders; average--------- 2.48(1 row)round(value, 2) leaves two decimal places; without the 2, it rounds to a whole number. AS average gives the column a name.
GROUP BY makes a summary for each group
Section titled “GROUP BY makes a summary for each group”How many orders are there in each status?
SELECT status, COUNT(*)FROM ordersGROUP BY statusORDER BY status; status | count---------+------- paid | 8 pending | 5 shipped | 12(3 rows)GROUP BY status splits the rows into groups, one for each different value of status, and COUNT(*) counts each group separately. One row comes out per group, and 8 + 5 + 12 are the 25 orders.
With a Join (combining tables)The part of an SQL query that puts together the rows of two tables that match on a condition, such as each order with its product. If a row matches several in the other table, it comes out once for each one.Go to definition from lesson 2 you can summarize data from two tables. How much each product has brought in, in units and in money:
SELECT p.name, SUM(o.quantity) AS units, SUM(o.quantity * p.price_cents) AS revenue_centsFROM orders AS oJOIN products AS p ON p.id = o.product_idGROUP BY p.id, p.nameORDER BY revenue_cents DESC; name | units | revenue_cents---------+-------+--------------- Hoodie | 20 | 70000 T-shirt | 20 | 40000 Mug | 22 | 18700(3 rows)Word by word:
FROM orders AS o JOIN products AS p ON …joins each order with its product: 25 rows, each with its quantity and its price.o.quantity * p.price_centsmultiplies in each row: what that order brought in.SUM(…)adds up those amounts inside each group. Money goes in whole cents, as in Phase 4: 70000 is €700.GROUP BY p.id, p.namemakes one group per product. It groups by theid, which is unique (two products could have the same name), and also by the name, so it can show it.ORDER BY revenue_cents DESCputs the one that brings in the most first.
The Mug sells the most units and brings in the least money. The Cap doesn’t show up: it has no orders, and the JOIN doesn’t pair it with anything.
What you select has to be grouped or summarized
Section titled “What you select has to be grouped or summarized”Ask for the status next to each product, but group only by product:
SELECT product_id, status, SUM(quantity)FROM ordersGROUP BY product_id;ERROR: column "orders.status" must appear in the GROUP BY clause or be used in an aggregate functionLINE 1: SELECT product_id, status, SUM(quantity) ^The ^ points at where the problem is. Product 1’s group has shipped, paid and pending orders: which one would it write in its single row? PostgreSQL doesn’t pick one at random: it refuses.
Every column in the SELECT has to be in the GROUP BY or inside an aggregate. Here, either you add status to the GROUP BY (one group for each pair of product and status) or you take it out of the SELECT.
There’s one exception: if you group by a table’s Primary keyThe column, or group of columns, that identifies each row of a table. Its value can’t repeat or be missing, like an order number.Go to definition, PostgreSQL lets you use its other columns, because each id has a single name. In this lesson, the name goes in the GROUP BY anyway, so you can see it.
COUNT(*) counts rows; COUNT(column), values
Section titled “COUNT(*) counts rows; COUNT(column), values”To get the Cap to show up, you need the LEFT JOIN from lesson 2. And there, COUNT has a trap:
SELECT p.name, COUNT(*) AS rows, COUNT(o.id) AS ordersFROM products AS pLEFT JOIN orders AS o ON o.product_id = p.idGROUP BY p.id, p.nameORDER BY p.id; name | rows | orders---------+------+-------- T-shirt | 8 | 8 Mug | 9 | 9 Hoodie | 8 | 8 Cap | 1 | 0(4 rows)The Cap has 1 row and 0 orders. The LEFT JOIN gives it a row with the orders columns empty, in NULL, and COUNT(*) counts rows. COUNT(column) only counts the values that aren’t NULL, and in that row o.id is.
The other aggregates skip NULLs too: the average of 3, 5 and a NULL is 4, not 2.67.
WHERE filters rows; HAVING, groups
Section titled “WHERE filters rows; HAVING, groups”Which products have sold more than 16 units, not counting the pending orders?
SELECT p.name, SUM(o.quantity) AS unitsFROM orders AS oJOIN products AS p ON p.id = o.product_idWHERE o.status <> 'pending'GROUP BY p.id, p.nameHAVING SUM(o.quantity) > 16ORDER BY p.name; name | units---------+------- Mug | 17 T-shirt | 17(2 rows)Two filters, at two moments:
WHERE o.status <> 'pending'removes rows before grouping: the pending orders don’t reach any group.HAVING SUM(o.quantity) > 16removes groups after: the Hoodie, with 16, is left out.
HAVING exists because WHERE can’t use a summary:
SELECT product_id, SUM(quantity)FROM ordersWHERE SUM(quantity) > 16GROUP BY product_id;ERROR: aggregate functions are not allowed in WHERELINE 3: WHERE SUM(quantity) > 16 ^When WHERE runs, there are no groups to add up yet.
A query doesn’t run in the order it’s written
Section titled “A query doesn’t run in the order it’s written”You write SELECT first, but PostgreSQL works it out almost at the end. This is the order of each part:
- FROM and JOINjoin the tables
all the rows
- WHEREremoves rows
the rows that are left
- GROUP BYmakes the groups
a summary per group
- HAVINGremoves groups
the groups that are left
- SELECTworks out the columns and their aliases
the result
- ORDER BYsorts it
sorted
- LIMITkeeps the first rows
Inside, PostgreSQL may work in a different way (you’ll see it in lesson 7, “Indexes”), but the result is always that of this order. With it, the earlier errors make sense: WHERE comes before GROUP BY and can’t add up groups; HAVING comes after, and can. And one more, very common: using a SELECT alias in WHERE.
SELECT name, price_cents / 100.0 AS eurosFROM productsWHERE euros > 10;ERROR: column "euros" does not existLINE 3: WHERE euros > 10; ^euros is born in the SELECT, which comes after the WHERE: when WHERE looks for it, it doesn’t exist. Compare with the table’s column instead, WHERE price_cents > 1000. ORDER BY comes after the SELECT and can use the alias: that’s why ORDER BY revenue_cents worked.
By the way, / 100.0 divides with decimals. Between two whole numbers, 850 / 100 gives 8: PostgreSQL drops the decimals.
The best day, counted in UTC
Section titled “The best day, counted in UTC”For the best day, group by the day of created_at:
SELECT (o.created_at AT TIME ZONE 'UTC')::date AS day, SUM(o.quantity * p.price_cents) AS revenue_centsFROM orders AS oJOIN products AS p ON p.id = o.product_idGROUP BY (o.created_at AT TIME ZONE 'UTC')::dateORDER BY revenue_cents DESCLIMIT 3; day | revenue_cents------------+--------------- 2026-10-07 | 20550 2026-10-04 | 20250 2026-10-01 | 20200(3 rows)o.created_at AT TIME ZONE 'UTC'gives the date and time a clock in UTC showed at that instant.::datechanges the type of that value todate, a day with no time:2026-10-07.::is PostgreSQL’s way of converting a value to another type.- The
GROUP BYrepeats the whole expression. PostgreSQL also acceptsGROUP BY day, even though the alias is born later: it’s a convenience of its own, not standard SQL, and other databases, like SQL Server, reject it.
Why UTC? created_at is a timestamptz: it stores an instant, not a day. Which day it was depends on the clock you look at. The order placed at 1:00 UTC on October 6 was placed at 9:00 p.m. on the 5th in New York. With 'America/New_York', the same query gives:
day | revenue_cents------------+--------------- 2026-10-05 | 26350 2026-10-07 | 22550 2026-10-01 | 20200(3 rows)The best day is now the 5th, and the 7th drops to second place, with a different figure.
Without AT TIME ZONE, ::date uses the connection’s time zone. Your shop role’s is UTC because you set it in the introduction, but a freshly installed PostgreSQL on a Mac uses the computer’s. Always say which time zone you count the days in. The shop counts in UTC, just as it has sent its dates since Phase 4.
A subquery in WHERE compares each row with a summary
Section titled “A subquery in WHERE compares each row with a summary”Which orders have more units than the average? The direct way fails:
SELECT id, product_id, quantityFROM ordersWHERE quantity > AVG(quantity);ERROR: aggregate functions are not allowed in WHERELINE 3: WHERE quantity > AVG(quantity); ^It’s the error from before. But you can work out the average in another query and use its result:
SELECT id, product_id, quantityFROM ordersWHERE quantity > (SELECT AVG(quantity) FROM orders)ORDER BY id; id | product_id | quantity----+------------+---------- 2 | 3 | 3 3 | 1 | 4 6 | 1 | 3 7 | 2 | 4 10 | 2 | 3 11 | 3 | 4 14 | 3 | 3 15 | 1 | 4 18 | 1 | 3 19 | 2 | 4 22 | 2 | 3 23 | 3 | 4(12 rows)(SELECT AVG(quantity) FROM orders) is a SubqueryA query written in parentheses inside another one. The database works it out and the outer query uses its result, for example to compare each row with an average or to read from it as if it were a table.Go to definition: a query in parentheses inside another one. PostgreSQL solves it, gets 2.48, and the outer one compares each order with that number. The ones with 3 and 4 units come out.
Here the subquery returns a single value, because > compares with one. If it returns a list, you use IN (“is in”): “the orders of any product in category 1, Clothing.”
SELECT COUNT(*)FROM ordersWHERE product_id IN (SELECT product_id FROM product_categories WHERE category_id = 1); count------- 16(1 row)The subquery gives the Clothing products: 1, 3 and 4. IN keeps the orders whose product_id is in that list: 8 for the T-shirt, 8 for the Hoodie and none for the Cap.
A subquery in FROM is an intermediate table
Section titled “A subquery in FROM is an intermediate table”How many units does each product sell on average? You have to add up per product and then take the average of those sums. An aggregate inside another doesn’t work:
SELECT AVG(SUM(quantity))FROM ordersGROUP BY product_id;ERROR: aggregate function calls cannot be nestedLINE 1: SELECT AVG(SUM(quantity)) ^The solution: the query that adds up per product goes in the FROM, and the outer one reads it as if it were a table:
SELECT round(AVG(units), 1) AS averageFROM ( SELECT product_id, SUM(quantity) AS units FROM orders GROUP BY product_id) AS per_product; average--------- 20.7(1 row)- The subquery gives one row per product, with its units: 20, 22 and 20.
AS per_productgives that intermediate table a name.round(AVG(units), 1)takes the average of the three sums, with one decimal place. Withoutround,20.6666666666666667.
The Cap doesn’t count: with no orders, it has no row in the subquery, and the average is of three products, not four.
Try it
Section titled “Try it”The goal: put together Ana’s report yourself. How much each product brings in, which was the best day and which orders are bigger than usual. Each query goes in the playground, the PostgreSQL in your browser, and in psql: open psql -d shop, as in the introduction, and type them after the shop=> prompt. If you changed data in lesson 1, load shop.sql again; in the playground, press “Reset data”.
Sales per product
Section titled “Sales per product”playground · PostgreSQL in your browser
A real PostgreSQL, with the shop’s data. What you change stays on this page.
Press “Run” and check that the Hoodie comes out first, with 70000. Then change it:
- Add
WHERE o.status = 'shipped'right before theGROUP BY: only what has already left the warehouse. - Change the first
SUMtoAVG: the average units per order, with its 16 decimal places. Fix them withround. - Add
o.statusto theSELECTwithout touching theGROUP BY, and read the error.
1. Sales per product, in psql
SELECT p.name, SUM(o.quantity) AS units, SUM(o.quantity * p.price_cents) AS revenue_centsFROM orders AS oJOIN products AS p ON p.id = o.product_idGROUP BY p.id, p.nameORDER BY revenue_cents DESC;What you will see:
name | units | revenue_cents---------+-------+---------------Hoodie | 20 | 70000T-shirt | 20 | 40000Mug | 22 | 18700(3 rows)psql doesn’t run anything until the ; arrives, so you can type it over several lines. If you get relation "orders" does not exist, you haven’t loaded the shop’s data: go back to the introduction. The outputs are from PostgreSQL 18.6; if yours answers in another language, you’ll see the same numbers with the messages translated.
The best day
Section titled “The best day”2. The day the most money came in
SELECT (o.created_at AT TIME ZONE 'UTC')::date AS day, SUM(o.quantity * p.price_cents) AS revenue_centsFROM orders AS oJOIN products AS p ON p.id = o.product_idGROUP BY (o.created_at AT TIME ZONE 'UTC')::dateORDER BY revenue_cents DESCLIMIT 1;What you will see:
day | revenue_cents------------+---------------2026-10-07 | 20550(1 row)October 7, with €205.50. Change 'UTC' to 'America/New_York' on both lines: the best day becomes October 5, with 26350. If you change it on only one, you get column "o.created_at" must appear in the GROUP BY clause: the SELECT and the GROUP BY have to carry the same expression.
Orders above the average
Section titled “Orders above the average”playground · PostgreSQL in your browser
A real PostgreSQL, with the shop’s data. What you change stays on this page.
You get 12. Now change AVG to MAX: no order is bigger than the biggest one, and you get (0 rows). Change > to = as well and you’ll have the shop’s biggest orders.
3. Orders above the average, in psql
SELECT id, product_id, quantityFROM ordersWHERE quantity > (SELECT AVG(quantity) FROM orders)ORDER BY id;What you will see:
id | product_id | quantity----+------------+----------2 | 3 | 33 | 1 | 46 | 1 | 37 | 2 | 410 | 2 | 311 | 3 | 414 | 3 | 315 | 1 | 418 | 1 | 319 | 2 | 422 | 2 | 323 | 3 | 4(12 rows)They all have 3 or 4 units: the average is 2.48. If you’ve changed orders, the average and the list will be different.
Challenge: on which day were the most mugs sold, in units? The Mug is product 2. Count the days in UTC.Show answer
First WHERE keeps only the mugs; then, one group per day:
SELECT (created_at AT TIME ZONE 'UTC')::date AS day, SUM(quantity) AS mugsFROM ordersWHERE product_id = 2GROUP BY (created_at AT TIME ZONE 'UTC')::dateORDER BY mugs DESCLIMIT 1; day | mugs------------+------ 2026-10-04 | 5(1 row)October 4, with 5 mugs. It’s not a HAVING: the filter is by product, a column of each row, so it goes in WHERE.
You have already seen it
Section titled “You have already seen it”- Pivot tables in Excel or Google Sheets: you choose which column to group by and what to summarize (sum, count, average). It’s a
GROUP BYwith the mouse. - The spending summary in your banking app: how much on groceries and how much on transportation this month. A
WHEREon dates, aGROUP BYon category and aSUM. - “Page 3 of 1,200”, from Phase 4: that total is a
COUNT(*), and that’s why it has a cost: to count, the database goes through every row that matches the filter.
Common mistakes
Section titled “Common mistakes”- Putting a column in the
SELECTthat’s neither in theGROUP BYnor inside an aggregate. Group it or summarize it. - Filtering a summary with
WHERE. Rows are filtered withWHERE; groups, withHAVING. - Counting with
COUNT(*)after aLEFT JOIN. What has nothing comes out with 1: count a column of the table on the right, likeCOUNT(o.id). - Using a
SELECTalias inWHERE. It doesn’t exist yet: repeat the operation or compare with the column. - Grouping by day without saying the time zone. The same report gives different numbers on your computer and on the server.
- Dividing two whole numbers:
850 / 100gives8. Use100.0. - Working out past sales with today’s price, as this lesson does. If the Hoodie’s price goes up tomorrow, last week’s sales change. A real shop stores in each order the price it was sold at (lesson 4).
Summary
Section titled “Summary”- An aggregate function (
COUNT,SUM,AVG,MIN,MAX) sums up many rows into one value.COUNT(*)counts rows;COUNT(column)and the others skipNULLs. GROUP BYmakes a summary per group. Every column in theSELECThas to be grouped or summarized.WHEREremoves rows before grouping andHAVINGremoves groups after.- The real order is
FROM,WHERE,GROUP BY,HAVING,SELECT,ORDER BYandLIMIT: that’s whyWHEREsees neither the aggregates nor the aliases. - A subquery is a query inside another one: in
WHERE, to compare with a summary; inFROM, to summarize a summary.
Did you get it?
Section titled “Did you get it?”To review:
Further reading
Section titled “Further reading”- Aggregate Functions (PostgreSQL): the official tutorial on aggregates,
GROUP BYandHAVING. - Aggregate Functions (PostgreSQL): every aggregate function, with what each one does with
NULLs. - The GROUP BY and HAVING Clauses (PostgreSQL): the exact rules, with the primary key exception.
- Subquery Expressions (PostgreSQL):
IN,EXISTSand the other ways of using a subquery. - AT TIME ZONE (PostgreSQL): how it converts dates between time zones.