Databases · Beginner · 15 min
Summarise data in SQL with GROUP BY, HAVING and aggregates
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · PostgreSQL 18.7
You will turn twelve order rows into a PostgreSQL 18 revenue report by month and region, with subtotals, saved as a view and a CSV file that matches a hand check.
On this page
Most questions a business asks of its database are summaries: how much did we sell last month, which region is growing, how many orders were refunded. SQL answers them with aggregate functions and GROUP BY, which collapse many rows into one row per group.
In this tutorial you load twelve orders from shops in Lagos, Nairobi and Accra, then build up to a monthly revenue report with a subtotal for each month and a grand total. The data is small on purpose, so you can add up every figure by hand and know the SQL is right. Along the way you meet the error every beginner hits ("must appear in the GROUP BY clause") and learn why it happens.
The tutorial uses PostgreSQL 18, installed as in /tutorials/install-postgresql-18-on-ubuntu-26-04. PostgreSQL 19 came out in November 2026; everything here works the same on it.
Step 1 · Create a practice database of orders
Create a database called shop and an orders table. Each row is one order: who placed it, which region's shop took it, whether it was paid or refunded, the amount, an optional coupon code and when it was placed.
sudo -u postgres createdb shop
sudo -u postgres psql -d shop <<'SQL'
CREATE TABLE orders (
id integer PRIMARY KEY,
customer text NOT NULL,
region text NOT NULL,
status text NOT NULL CHECK (status IN ('paid', 'refunded')),
amount numeric(10, 2) NOT NULL,
coupon text,
ordered_at timestamp NOT NULL
);
INSERT INTO orders VALUES
(1, 'Ada', 'Lagos', 'paid', 120.00, 'SAVE10', '2026-08-03 10:15'),
(2, 'Bayo', 'Lagos', 'paid', 80.00, NULL, '2026-08-15 14:02'),
(3, 'Wanjiru', 'Nairobi', 'paid', 200.00, NULL, '2026-08-20 09:40'),
(4, 'Kofi', 'Accra', 'refunded', 50.00, NULL, '2026-08-28 17:25'),
(5, 'Ada', 'Lagos', 'paid', 60.00, NULL, '2026-09-02 11:00'),
(6, 'Amina', 'Nairobi', 'paid', 150.00, 'SAVE10', '2026-09-09 16:30'),
(7, 'Kofi', 'Accra', 'paid', 90.00, NULL, '2026-09-12 08:55'),
(8, 'Wanjiru', 'Nairobi', 'paid', 40.00, NULL, '2026-09-30 23:10'),
(9, 'Bayo', 'Lagos', 'paid', 300.00, 'SAVE10', '2026-10-05 13:45'),
(10, 'Esi', 'Accra', 'paid', 70.00, NULL, '2026-10-11 10:20'),
(11, 'Amina', 'Nairobi', 'refunded', 100.00, NULL, '2026-10-19 15:05'),
(12, 'Chidi', 'Lagos', 'paid', 30.00, NULL, '2026-10-25 19:50');
SQLThe amount column is numeric(10, 2), an exact decimal type. Use it for money; real and double precision round in binary and a column of them can sum to 1139.9999999. All amounts here are in one currency. If your shops sell in naira, shillings and cedis, add a currency column and group by it too: a sum across currencies means nothing.
Every command in this tutorial runs SQL through sudo -u postgres psql. If you prefer an interactive session, run sudo -u postgres psql -d shop and type the SQL at the shop=# prompt.
Check it worked
sudo -u postgres psql -d shop -c "SELECT count(*) FROM orders;"The result is one row with 12 in it.
Step 2 · Collapse the whole table with aggregate functions
An aggregate function takes many rows and returns one value. Without GROUP BY, the whole table is one group, so you get exactly one row back.
sudo -u postgres psql -d shop <<'SQL'
SELECT count(*) AS all_orders,
count(coupon) AS with_coupon,
count(DISTINCT customer) AS customers,
sum(amount) AS total,
round(avg(amount), 2) AS average,
min(amount) AS smallest,
max(amount) AS largest
FROM orders;
SQL all_orders | with_coupon | customers | total | average | smallest | largest
------------+-------------+-----------+---------+---------+----------+---------
12 | 3 | 7 | 1290.00 | 107.50 | 30.00 | 300.00The first two columns show the difference that trips people up:
count(*)counts rows, all twelve.count(coupon)counts rows wherecouponis not NULL. Only orders 1, 6 and 9 used a coupon, so it says 3.count(DISTINCT customer)counts different values once each. Ada, Bayo, Wanjiru, Kofi, Amina, Esi and Chidi make 7.
sum, avg, min and max also skip NULLs. That matters for avg: averaging a column with gaps divides by the number of non-NULL values, not by the row count. avg of a numeric column returns many decimal places, so wrap it in round(..., 2) for display.
Check it worked
Add the twelve amounts yourself: 120 + 80 + 200 + 50 + 60 + 150 + 90 + 40 + 300 + 70 + 100 + 30 = 1290. Divided by 12 that is 107.50. Both match the output.
Step 3 · Group rows by one column
GROUP BY region splits the rows into one group per region and runs the aggregates once for each group. Add WHERE status = 'paid' so refunded orders stay out of revenue.
sudo -u postgres psql -d shop <<'SQL'
SELECT region,
count(*) AS orders,
sum(amount) AS revenue
FROM orders
WHERE status = 'paid'
GROUP BY region
ORDER BY revenue DESC;
SQL region | orders | revenue
---------+--------+---------
Lagos | 5 | 590.00
Nairobi | 3 | 390.00
Accra | 2 | 160.00PostgreSQL runs the clauses in this order, whatever order you write them in: FROM, then WHERE (drop rows), then GROUP BY (form groups), then the aggregates in SELECT, then ORDER BY. That is why ORDER BY can use the revenue alias and why WHERE cannot see any totals.
Grouping on text is exact. Lagos, lagos and Lagos ` (with a trailing space) are three different groups. If regions are typed in by people, possibly in several languages or spellings, clean them on the way in or group on a cleaned value such as `lower(trim(region)).
Check it worked
There are three rows, and 590 + 390 + 160 = 1140, which is the 1290 total minus the two refunds (50 and 100).
Step 4 · Understand the "must appear in the GROUP BY clause" error
Try asking for each region's revenue and the customer's name in the same query:
sudo -u postgres psql -d shop <<'SQL'
SELECT region, customer, sum(amount)
FROM orders
GROUP BY region;
SQLPostgreSQL refuses, with something like:
ERROR: column "orders.customer" must appear in the GROUP BY clause or be used in an aggregate functionThe Lagos group holds five orders from Ada, Bayo and Chidi. The result has one row for Lagos, and that row has one customer cell. PostgreSQL has no way to pick which name goes in it, so it stops instead of guessing. Every column in SELECT must either be in GROUP BY (one value per group by definition) or sit inside an aggregate (many values folded into one).
You have three ways out, depending on the question you meant to ask:
- You want one row per region and customer: add
customertoGROUP BY. - You want one name per region: use an aggregate, such as
min(customer)orstring_agg(DISTINCT customer, ', ')for a list. - You want each order's detail next to its region total: that is a window function, covered in
/tutorials/answer-ranking-and-running-total-questions-with-sql-window-functions.
One exception is worth knowing. If you group by a table's primary key, PostgreSQL lets you select any other column of that table, because the key fixes each one to a single value.
Check it worked
Run the query again with string_agg(DISTINCT customer, ', ') in place of customer. It now succeeds, and the Lagos row lists Ada, Bayo, Chidi.
Step 5 · Group by month and region
A monthly report needs to group by a month, not by the exact timestamp. date_trunc('month', ordered_at) rounds each timestamp down to midnight on the first of its month, so every August order gets the same value. Group by that and by region together:
sudo -u postgres psql -d shop <<'SQL'
SELECT date_trunc('month', ordered_at)::date AS month,
region,
count(*) AS orders,
sum(amount) AS revenue
FROM orders
WHERE status = 'paid'
GROUP BY month, region
ORDER BY month, region;
SQL month | region | orders | revenue
------------+---------+--------+---------
2026-08-01 | Lagos | 2 | 200.00
2026-08-01 | Nairobi | 1 | 200.00
2026-09-01 | Accra | 1 | 90.00
2026-09-01 | Lagos | 1 | 60.00
2026-09-01 | Nairobi | 2 | 190.00
2026-10-01 | Accra | 1 | 70.00
2026-10-01 | Lagos | 2 | 330.00With two columns in GROUP BY, a group is each combination of month and region that occurs in the data. Notice what is missing: Accra in August and Nairobi in October. Their only orders that month were refunds, which WHERE removed, so there is no group to report. GROUP BY never invents empty groups. If a report must show zero rows, join against a list of months and regions instead.
GROUP BY month uses the output alias from SELECT. PostgreSQL allows that; you can also repeat the full expression. The ::date cast only trims the display from a timestamp to a date. If your column is timestamptz, date_trunc uses the session's time zone to decide where a month starts, so set it (SET TIME ZONE 'Africa/Lagos';, for example) before running month reports.
Check it worked
Seven rows appear, and the revenue column adds up to 1140.00, the same paid total as the previous step.
Step 6 · Filter groups with HAVING
WHERE filters rows before they are grouped. HAVING filters groups after the aggregates are worked out. Use both in one query to find repeat customers: paid orders only (a row rule), then only customers with two or more of them (a group rule).
sudo -u postgres psql -d shop <<'SQL'
SELECT customer,
count(*) AS paid_orders,
sum(amount) AS spent
FROM orders
WHERE status = 'paid'
GROUP BY customer
HAVING count(*) >= 2
ORDER BY spent DESC;
SQL customer | paid_orders | spent
----------+-------------+--------
Bayo | 2 | 380.00
Wanjiru | 2 | 240.00
Ada | 2 | 180.00A quick way to choose between the two: if the condition mentions an aggregate (count, sum and the rest), it belongs in HAVING. Put it in WHERE and PostgreSQL rejects it with an error saying aggregate functions are not allowed in WHERE. If the condition is about single rows, put it in WHERE; it is clearer and lets PostgreSQL throw rows away early. HAVING cannot use the paid_orders alias, so repeat the aggregate there.
Check it worked
Kofi has two orders, but one was refunded, so he is filtered out by WHERE before HAVING sees him. Amina is out for the same reason. The three names left are Bayo, Wanjiru and Ada.
Step 7 · Count several conditions in one pass with FILTER
WHERE status = 'paid' throws the refunds away, but a manager also wants to see them. Rather than run one query per condition, attach FILTER (WHERE ...) to each aggregate. Each aggregate then only sees the rows that pass its own filter, and the table is read once.
sudo -u postgres psql -d shop <<'SQL'
SELECT region,
count(*) AS all_orders,
count(*) FILTER (WHERE status = 'refunded') AS refunds,
coalesce(sum(amount) FILTER (WHERE status = 'refunded'), 0) AS refunded_value,
sum(amount) FILTER (WHERE status = 'paid') AS paid_revenue,
count(*) FILTER (WHERE coupon IS NOT NULL) AS with_coupon
FROM orders
GROUP BY region
ORDER BY region;
SQL region | all_orders | refunds | refunded_value | paid_revenue | with_coupon
---------+------------+---------+----------------+--------------+-------------
Accra | 3 | 1 | 50.00 | 160.00 | 0
Lagos | 5 | 0 | 0 | 590.00 | 2
Nairobi | 4 | 1 | 100.00 | 390.00 | 1Watch the Lagos row. A filtered count with no matching rows returns 0, but a filtered sum returns NULL, because there was nothing to add. coalesce(..., 0) turns that NULL into 0 so the column reads cleanly.
Check it worked
The all_orders column adds up to 12, refunds to 2, and paid_revenue matches the per-region figures from the "Group rows by one column" step.
Step 8 · Add totals with GROUPING SETS and ROLLUP
GROUPING SETS runs several groupings in one query and stacks the results. The query below asks for three at once: totals per month, totals per region, and (), the empty grouping, which is the grand total. A WITH clause works out the month once so the main query stays short.
sudo -u postgres psql -d shop <<'SQL'
WITH paid AS (
SELECT date_trunc('month', ordered_at)::date AS month, region, amount
FROM orders
WHERE status = 'paid'
)
SELECT month, region, sum(amount) AS revenue
FROM paid
GROUP BY GROUPING SETS ((month), (region), ())
ORDER BY month NULLS LAST, region NULLS LAST;
SQL month | region | revenue
------------+---------+---------
2026-08-01 | | 400.00
2026-09-01 | | 340.00
2026-10-01 | | 400.00
| Accra | 160.00
| Lagos | 590.00
| Nairobi | 390.00
| | 1140.00A column that is not part of a row's grouping comes back as NULL, which psql shows as a blank. A month total has no region, a region total has no month, and the grand total has neither.
ROLLUP (month, region) is shorthand for the grouping sets a report with subtotals needs: (month, region), then (month), then (). That is the detail rows, a subtotal for each month, and a grand total.
There is a catch. If region could be NULL in your real data, a blank would mean either "no region recorded" or "subtotal", and you could not tell which. The GROUPING(column) function settles it: it returns 1 when the column was rolled up for that row and 0 when it holds a real value. The next step uses it to print readable labels.
Check it worked
The three month totals add up to 1140, and so do the three region totals. Both match the grand total in the last row.
Step 9 · Save the monthly report as a view and a CSV file
Put the finished report in a view, so anyone with access can run SELECT * FROM monthly_revenue instead of copying a long query. It uses ROLLUP for the subtotals and GROUPING() for the labels.
sudo -u postgres psql -d shop <<'SQL'
CREATE VIEW monthly_revenue AS
WITH paid AS (
SELECT date_trunc('month', ordered_at)::date AS month, region, amount
FROM orders
WHERE status = 'paid'
)
SELECT CASE WHEN GROUPING(paid.month) = 1 THEN 'All months'
ELSE to_char(paid.month, 'YYYY-MM') END AS month,
CASE WHEN GROUPING(paid.region) = 1 THEN 'All regions'
ELSE paid.region END AS region,
count(*) AS orders,
sum(paid.amount) AS revenue
FROM paid
GROUP BY ROLLUP (paid.month, paid.region)
ORDER BY paid.month NULLS LAST, GROUPING(paid.region), paid.region;
SQLThe output columns are called month and region, the same names as the columns of paid. Writing paid.month and paid.region everywhere else makes it plain that grouping and sorting use the real date and region, not the text labels. Sorting on the date keeps months in calendar order; GROUPING(paid.region) puts each subtotal after its month's detail rows.
Export the view to a CSV file you can open in a spreadsheet or send to a colleague. The file is a few hundred bytes, which matters when it travels over a metered mobile connection.
mkdir -p ~/group-by-demo
sudo -u postgres psql -d shop --csv -c "SELECT * FROM monthly_revenue;" > ~/group-by-demo/monthly-revenue.csv
cat ~/group-by-demo/monthly-revenue.csvmonth,region,orders,revenue
2026-08,Lagos,2,200.00
2026-08,Nairobi,1,200.00
2026-08,All regions,3,400.00
2026-09,Accra,1,90.00
2026-09,Lagos,1,60.00
2026-09,Nairobi,2,190.00
2026-09,All regions,4,340.00
2026-10,Accra,1,70.00
2026-10,Lagos,2,330.00
2026-10,All regions,3,400.00
All months,All regions,10,1140.00The redirect > runs as your own user, so the file belongs to you, not to postgres.
Check it worked
Check one cell against the raw rows. List Lagos's paid orders in October:
sudo -u postgres psql -d shop <<'SQL'
SELECT id, customer, amount
FROM orders
WHERE region = 'Lagos'
AND status = 'paid'
AND ordered_at >= '2026-10-01'
AND ordered_at < '2026-11-01'
ORDER BY id;
SQLTwo rows come back, Bayo's 300.00 and Chidi's 30.00. They add up to 330.00, the same as the 2026-10,Lagos line in the CSV. The date range is written as "on or after the 1st, before the 1st of next month" rather than with BETWEEN, so an order at 23:59 on 31 October is never lost.
Then check the bottom line against a plain sum:
sudo -u postgres psql -d shop -c "SELECT sum(amount) FROM orders WHERE status = 'paid';"It prints 1140.00, the same as the All months,All regions row.
Step 10 · Remove the practice database
When you have finished experimenting, drop the shop database (this deletes the orders table and the view with it) and remove the demo folder. Keep the CSV first if you want it.
sudo -u postgres dropdb shop
rm -r ~/group-by-demoCheck it worked
sudo -u postgres psql -Atc "SELECT count(*) FROM pg_database WHERE datname = 'shop';"It prints 0, and ls ~/group-by-demo reports that the folder does not exist.
Next steps
- Bring customer and product details into the same report by joining tables:
/tutorials/combine-tables-with-sql-joins. - Rank regions within each month and add running totals without collapsing rows:
/tutorials/answer-ranking-and-running-total-questions-with-sql-window-functions. - When a report over millions of rows gets slow, read its plan:
/tutorials/speed-up-slow-postgres-queries-with-explain.
Related tutorials
- Combine tables with SQL joins: inner, left, self and anti-joinsYou will join customers, orders, products and reviews in PostgreSQL 18, predict which rows each kind of join keeps, find customers who never ordered, and spot the join that silently doubles your counts.
- Answer ranking and running-total questions with SQL window functionsYou will use PostgreSQL 18 window functions to rank products per region with ties handled on purpose, keep running totals and 7-day averages, compare each month with the one before, and save the answers in a report file you can run again.
- How to Install PostgreSQL 18 on Ubuntu 26.04 and Create Your First DatabaseYou will install PostgreSQL 18 from the official PostgreSQL apt repository, create a database and a user for your app, and connect to it with a password.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials