GROUP BY
Overview
The last lesson collapsed a whole table into one row. That answers “how many orders do we have?”, but most real questions are per something: orders per status, revenue per product, customers per country, sales per month. GROUP BY splits the rows into groups and runs the aggregates once for each group.
One row per group
How many products are in each category?
SELECT category_id, count(*) AS products
FROM products
GROUP BY category_id
ORDER BY category_id; category_id | products
-------------+----------
1 | 3
2 | 4
3 | 4
| 1
(4 rows)Here’s what happened, step by step:
FROM productsread all twelve rows.GROUP BY category_idsorted them into piles — one pile for each differentcategory_id.count(*)counted each pile.- The result has one row per pile.
The gift card’s NULL category forms a group of its own — GROUP BY treats all NULLs as one group. The diagram shows the same query with category names instead of ids; that needs a join, which you’ll learn in chapter 5.
Several aggregates per group
Any number of aggregates can run on each group:
SELECT status,
count(*) AS orders,
sum(shipping_fee) AS shipping,
min(ordered_at)::date AS first,
max(ordered_at)::date AS latest
FROM orders
GROUP BY status
ORDER BY orders DESC; status | orders | shipping | first | latest
-----------+--------+----------+------------+------------
delivered | 16 | 90.72 | 2026-01-05 | 2026-09-19
cancelled | 2 | 14.49 | 2026-02-14 | 2026-06-25
pending | 2 | 9.50 | 2026-11-20 | 2026-11-29
paid | 2 | 11.49 | 2026-10-27 | 2026-11-08
shipped | 2 | 13.24 | 2026-09-01 | 2026-10-03
(5 rows)Notice ORDER BY orders DESC: you can sort by an aggregate’s alias, which is how “top N” lists are built.
The golden rule
In a grouped query, every column in SELECT must be either listed in GROUP BY or inside an aggregate. The reason is the same as in the last lesson: each result row represents a whole group, so a column has to have one value per group.
SELECT category_id, name, count(*)
FROM products
GROUP BY category_id;ERROR: column "products.name" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: SELECT category_id, name, count(*)
^Category 2 has four different names — which one would go in its single row? If you want them all, aggregate them:
SELECT category_id,
count(*) AS products,
string_agg(name, ', ' ORDER BY name) AS names
FROM products
GROUP BY category_id
ORDER BY category_id; category_id | products | names
-------------+----------+------------------------------------------------------------------------
1 | 3 | Colombian Supremo, Decaf House Blend, Ethiopian Yirgacheffe
2 | 4 | Assam Breakfast, Chamomile Calm, Darjeeling First Flush, Jasmine Green
3 | 4 | Burr Grinder, Electric Kettle, Glass Teapot, Pour-Over Dripper
| 1 | Gift Card
(4 rows)One exception: if you group by a table’s primary key, PostgreSQL knows each group is a single row of that table, so you may select that table’s other columns without listing them. You’ll use that with joins.
Grouping by several columns
List more than one column to get one row per combination:
SELECT country, city, count(*) AS customers
FROM customers
GROUP BY country, city
ORDER BY country, city; country | city | customers
-----------+-----------+-----------
France | Lyon | 1
India | Mumbai | 1
India | Pune | 2
Nigeria | Lagos | 1
Singapore | Singapore | 1
Spain | Madrid | 1
UK | Leeds | 1
USA | Austin | 1
USA | Seattle | 1
(9 rows)Pune has two customers; every other city has one. The order of the columns in GROUP BY doesn’t change the groups, only how you choose to sort them.
Grouping by an expression
You can group by anything you can calculate. Orders per month uses date_trunc from Dates and times:
SELECT date_trunc('month', ordered_at)::date AS month,
count(*) AS orders
FROM orders
GROUP BY date_trunc('month', ordered_at)
ORDER BY month; month | orders
------------+--------
2026-01-01 | 3
2026-02-01 | 3
2026-03-01 | 3
2026-04-01 | 2
2026-05-01 | 2
2026-06-01 | 2
2026-07-01 | 1
2026-08-01 | 1
2026-09-01 | 2
2026-10-01 | 2
2026-11-01 | 3
(11 rows)Repeating the expression in GROUP BY is a little verbose. PostgreSQL also lets you group by the alias or the column’s position — GROUP BY month or GROUP BY 1 — which are common in practice:
SELECT CASE WHEN price >= 50 THEN 'premium'
WHEN price >= 15 THEN 'standard'
ELSE 'budget' END AS band,
count(*) AS products,
round(avg(price), 2) AS avg_price
FROM products
GROUP BY band
ORDER BY avg_price; band | products | avg_price
----------+----------+-----------
budget | 6 | 11.33
standard | 4 | 24.75
premium | 2 | 74.45
(3 rows)That’s the price bands from CASE expressions, counted. (Grouping by an alias is a PostgreSQL convenience; standard SQL and some other databases require the full expression.)
WHERE runs before grouping
WHERE filters individual rows before they’re grouped. Here are the line count, units and items total for each of the first five orders:
SELECT order_id,
count(*) AS lines,
sum(quantity) AS units,
sum(quantity * unit_price) AS items_total
FROM order_items
WHERE order_id <= 5
GROUP BY order_id
ORDER BY order_id; order_id | lines | units | items_total
----------+-------+-------+-------------
1 | 2 | 3 | 38.50
2 | 2 | 3 | 113.00
3 | 1 | 1 | 18.00
4 | 2 | 4 | 62.25
5 | 1 | 1 | 59.90
(5 rows)Rows for orders above 5 were removed first; only then were the remaining rows grouped. To filter groups — “only orders with more than two lines” — you need HAVING, the next lesson.
Groups come from the data
GROUP BY can only produce groups for values that actually appear in the rows. The Accessories category has no products, so it’s missing from the first query in this lesson rather than showing a count of 0. Similarly, a month with no orders simply wouldn’t appear in the monthly report. When you need the empty groups too, you start from the table that lists every category (or a generated list of every month) and join — a technique you’ll see in Outer joins.
A complete report
Putting it together — per customer, how many orders, how much shipping, and when they last ordered:
SELECT customer_id,
count(*) AS orders,
count(*) FILTER (WHERE status = 'cancelled') AS cancelled,
sum(shipping_fee) AS shipping_paid,
max(ordered_at)::date AS last_order
FROM orders
GROUP BY customer_id
ORDER BY orders DESC, customer_id; customer_id | orders | cancelled | shipping_paid | last_order
-------------+--------+-----------+---------------+------------
1 | 5 | 0 | 4.99 | 2026-11-20
2 | 4 | 0 | 26.00 | 2026-10-27
3 | 3 | 0 | 24.00 | 2026-09-19
4 | 3 | 1 | 28.50 | 2026-11-29
6 | 3 | 1 | 14.97 | 2026-11-08
5 | 2 | 0 | 14.50 | 2026-07-08
7 | 2 | 0 | 11.98 | 2026-09-01
8 | 2 | 0 | 14.50 | 2026-10-03
(8 rows)Customer 1 (Asha) is the most frequent buyer — and, with free shipping on four of her five orders, has paid the least for it. Customers 9 and 10 don’t appear at all, because they’ve never ordered.
Tip: when writing a grouped query, decide first what one result row represents (“one row per customer”). That tells you what goes in
GROUP BY; everything else inSELECTmust then be an aggregate.
Best-selling products
Using only the order_items table, find the five products that brought in the most money. For each product_id, return units (total quantity sold), revenue (the sum of quantity × unit price) and orders (how many order lines it appears on). Sort by revenue, highest first, and break ties by product_id; return only the top five.
SELECT product_id
FROM order_items;SELECT product_id,
sum(quantity) AS units,
sum(quantity * unit_price) AS revenue,
count(*) AS orders
FROM order_items
GROUP BY product_id
ORDER BY revenue DESC, product_id
LIMIT 5;Summary
- GROUP BY splits the rows into groups that share the same value(s), and aggregates then produce one result row per group.
- Every column in SELECT must either be in GROUP BY or be inside an aggregate function.
- Group by several columns to get one row per combination, or by an expression such as date_trunc('month', ordered_at).
- WHERE filters rows before grouping; ORDER BY can sort by an aggregate such as count(*) DESC.
- NULLs form a group of their own, and groups only exist for values that appear in the data.