PostgreSQL GROUP BY
Aggregates such as count and sum collapse many rows into one value. GROUP BY makes them work per group: one result row for each distinct value (or combination of values) of the grouping columns.
One row per group
How many books does each category have?
SELECT category_id, count(*) AS books
FROM books
GROUP BY category_id
ORDER BY category_id; category_id | books
-------------+-------
1 | 5
2 | 3
3 | 3
4 | 4
5 | 3
6 | 2
(6 rows)
PostgreSQL sorts the 20 books into buckets by category_id, then runs count(*) inside each bucket.
The golden rule
Every column in the SELECT list must either be in the GROUP BY or be inside an aggregate function. Otherwise PostgreSQL doesn't know which of the group's values to show:
SELECT category_id, title, count(*)
FROM books
GROUP BY category_id;ERROR: column "books.title" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: SELECT category_id, title, count(*)
^
Note: If you group by a table's primary key, PostgreSQL knows every other column of that table is determined by it, so you may select those columns without listing them. That is why
GROUP BY c.idlets you also selectc.first_name.
Grouping with joins
Group by a readable name instead of an id by joining first. Revenue per customer for delivered orders:
SELECT c.id, c.first_name, c.last_name,
count(DISTINCT o.id) AS orders,
sum(oi.quantity * oi.unit_price) AS spent
FROM customers c
JOIN orders o ON o.customer_id = c.id
JOIN order_items oi ON oi.order_id = o.id
WHERE o.status = 'delivered'
GROUP BY c.id
ORDER BY spent DESC
LIMIT 5; id | first_name | last_name | orders | spent
----+------------+-----------+--------+--------
2 | Ben | Carter | 2 | 153.40
1 | Anna | Kowalski | 3 | 127.30
10 | Jamal | Wright | 1 | 79.00
6 | Farid | Haddad | 1 | 66.00
4 | David | Kim | 1 | 42.50
(5 rows)
Grouping by several columns or by expressions
With several columns, each distinct combination is a group. You can also group by an expression, such as the month of a date:
SELECT date_trunc('month', order_date)::date AS month,
status,
count(*) AS orders
FROM orders
WHERE order_date < '2024-05-01'
GROUP BY month, status
ORDER BY month, status; month | status | orders
------------+-----------+--------
2024-01-01 | delivered | 2
2024-02-01 | delivered | 2
2024-03-01 | cancelled | 1
2024-03-01 | delivered | 1
2024-04-01 | delivered | 2
(5 rows)
PostgreSQL lets you use the output alias (month) or the position (GROUP BY 1, 2) in GROUP BY.
Collecting values: string_agg and array_agg
Aggregates don't have to be numbers. string_agg joins text and array_agg builds an array, each with an optional ORDER BY:
SELECT a.name,
count(*) AS books,
string_agg(b.title, ' / ' ORDER BY b.published) AS titles,
array_agg(b.id ORDER BY b.id) AS ids
FROM authors a
JOIN books b ON b.author_id = a.id
GROUP BY a.id
HAVING count(*) >= 3
ORDER BY a.name; name | books | titles | ids
---------------+-------+--------------------------------------------------------------+------------
Daniel Reyes | 3 | Murder at Low Tide / The Quiet Witness / The Map Thief | {6,7,18}
Maria Okafor | 3 | Harbor Lights / The Salt Road / Starlight Kitchen | {1,2,20}
Tom Whitfield | 3 | The Age of Canals / Empires of Sand / A Short History of Tea | {11,12,19}
(3 rows)
Subtotals: ROLLUP
GROUP BY ROLLUP (a, b) adds subtotal rows for each a and a grand total, with NULL in the rolled-up columns:
SELECT status, count(*) AS orders
FROM orders
GROUP BY ROLLUP (status)
ORDER BY status NULLS LAST; status | orders
-----------+--------
cancelled | 2
delivered | 14
pending | 2
shipped | 2
| 20
(5 rows)
The last row (empty status) is the total of all orders. CUBE and GROUPING SETS give even more control over which subtotals appear.
Test yourself
What does GROUP BY country produce?
- One row per customer
- One row per distinct country
- Rows sorted by country
- A count of countries
Which select list is valid with GROUP BY category_id?
- category_id, title
- category_id, count(*)
- title, price
- *
Which function joins the titles of a group into one text value?
- concat()
- string_agg()
- array_agg()
- group_concat()