Grouping and counting
Most report tasks say “per channel”, “per month” or “per customer”. GROUP BY turns many rows into one row per group. The usual mistakes are the wrong grain, rows counted where customers were asked for, and a condition in the wrong clause.
One row per what
Section titled “One row per what”Before you write a query, say what one row of the result is. “Revenue per channel” is one row per channel. “Transactions per channel and plan period” is one row per pair. This grain decides the GROUP BY list. Every column in SELECT must be in that list or inside an aggregate: COUNT, SUM, AVG, MIN, MAX.
SELECT channel, plan_period, COUNT(*) AS transactionsFROM transactionsWHERE NOT is_test AND channel IN ('promo', 'web') AND start_time >= TIMESTAMP '2026-08-01' AND start_time < TIMESTAMP '2026-09-01'GROUP BY channel, plan_periodORDER BY channel, plan_period;| channel | plan_period | transactions |
|---|---|---|
| promo | P1M | 6 |
| promo | P1Y | 2 |
| web | P1M | 37 |
| web | P1W | 6 |
| web | P1Y | 8 |
A group exists only if it has rows. Promo access has no weekly plan in August, so there is no promo, P1W row with 0. To show such zeros, start from a list of all groups: see LEFT JOIN and zeros.
Will the query run?
Guess the result first, then run the query. Fix the query, then Check.
Output columns: country, channel, n
Tables, columns and how they connect
transactions — one row = one paid (or trial) period of a subscription
channel— north_market / south_market (partner marketplaces) / web (own checkout) / promo (free access, price 0)country— customer's country
| channel | country |
|---|---|
| north_market | IN |
| north_market | US |
| north_market | IN |
"Today" is 2026-09-30 00:00 UTC. All times are UTC. Every run is rolled back, so you cannot break the data.
SELECT country, channel, COUNT(*) AS n FROM transactions GROUP BY country;
Show answer
No: column "transactions.channel" must appear in the GROUP BY clause or be used in an aggregate function. One country has many channels, so which one should the row show? Add channel to GROUP BY, or put it inside an aggregate.
This is what PostgreSQL returns for the query as it is:
Show the fix
SELECT country, channel, COUNT(*) AS nFROM transactionsGROUP BY country, channel;| country | channel | n |
|---|---|---|
| GB | south_market | 284 |
| GE | north_market | 520 |
| GB | promo | 5 |
| US | south_market | 927 |
| US | promo | 67 |
| US | web | 261 |
| BR | promo | 4 |
| IN | north_market | 567 |
| BR | north_market | 518 |
| JP | north_market | 504 |
| BR | web | 93 |
| GB | north_market | 439 |
| DE | north_market | 548 |
| GE | south_market | 341 |
| IN | promo | 2 |
| GB | web | 96 |
| DE | promo | 5 |
| DE | south_market | 283 |
| US | north_market | 1498 |
| GE | web | 90 |
| GE | promo | 8 |
| JP | promo | 14 |
| IN | web | 81 |
| DE | web | 69 |
| JP | web | 50 |
| JP | south_market | 335 |
| IN | south_market | 310 |
| BR | south_market | 375 |
PostgreSQL relaxes the rule in one case. When you group by a table’s primary key, the other columns of that table may appear in SELECT without being listed: GROUP BY m.id is enough to show m.name. Listing both (GROUP BY m.id, m.name) is also fine and works in every database.
The order in which a query runs
Section titled “The order in which a query runs”A query is written in one order and runs in another:
| Step | Clause | What it works with |
|---|---|---|
| 1 | FROM, JOIN | the rows of the tables |
| 2 | WHERE | one row at a time |
| 3 | GROUP BY | rows that become groups |
| 4 | HAVING | one group at a time, with its aggregates |
| 5 | SELECT | output columns; aliases are born here |
| 6 | ORDER BY | the output, aliases included |
| 7 | LIMIT | the sorted output |
An alias is created in step 5, so WHERE and HAVING cannot see it yet.
Will the query run?
Guess the result first, then run the query. Fix the query, then Check.
Output columns: transaction_id, proceeds
Tables, columns and how they connect
transactions — one row = one paid (or trial) period of a subscription
transaction_id— unique id of the transactionrevenue_usd— revenue net of refunds: 0 if the transaction was refunded (net)fee_rate— channel fee: 0.15 / 0.30 on the marketplaces, 0.03 on web
| transaction_id | revenue_usd | fee_rate |
|---|---|---|
| t_000001 | 79.99 | 0.1500 |
| t_000002 | 2.99 | 0.1500 |
| t_000003 | 4.99 | 0.1500 |
"Today" is 2026-09-30 00:00 UTC. All times are UTC. Every run is rolled back, so you cannot break the data.
SELECT transaction_id,
revenue_usd * (1 - fee_rate) AS proceeds
FROM transactions
WHERE proceeds > 50;Show answer
No: column "proceeds" does not exist. WHERE runs before SELECT, so the alias does not exist yet. Repeat the expression in WHERE, or compute it in a CTE and filter outside.
This is what PostgreSQL returns for the query as it is:
Show the fix
WITH t AS ( SELECT transaction_id, revenue_usd * (1 - fee_rate) AS proceeds FROM transactions)SELECT transaction_id, proceedsFROM tWHERE proceeds > 50;| transaction_id | proceeds |
|---|---|
| t_004935 | 55.993000 |
| t_006474 | 67.991500 |
| t_004522 | 67.991500 |
| t_002111 | 50.991500 |
| t_000877 | 50.991500 |
| t_003763 | 67.991500 |
| t_004077 | 67.991500 |
| t_006547 | 67.991500 |
| t_004493 | 67.991500 |
| t_007002 | 67.991500 |
| t_002440 | 77.590300 |
| t_005357 | 67.991500 |
| t_002539 | 67.991500 |
| t_004673 | 55.993000 |
| t_008010 | 50.991500 |
| t_003126 | 50.991500 |
| t_002142 | 67.991500 |
| t_001621 | 67.991500 |
| t_001909 | 50.991500 |
| t_000323 | 67.991500 |
| t_000966 | 67.991500 |
| t_007556 | 50.991500 |
| t_003550 | 67.991500 |
| t_008215 | 67.991500 |
| t_003681 | 77.590300 |
| t_000774 | 67.991500 |
| t_000625 | 67.991500 |
| t_008282 | 55.993000 |
| t_004829 | 50.991500 |
| t_006283 | 67.991500 |
| t_000466 | 67.991500 |
| t_001696 | 50.991500 |
| t_005546 | 67.991500 |
| t_004988 | 67.991500 |
| t_005391 | 67.991500 |
| t_003382 | 67.991500 |
| t_004542 | 50.991500 |
| t_000619 | 67.991500 |
| t_006472 | 67.991500 |
| t_005894 | 58.190300 |
| t_002359 | 67.991500 |
| t_005808 | 67.991500 |
| t_004137 | 77.590300 |
| t_002445 | 67.991500 |
| t_000540 | 50.991500 |
| t_004890 | 67.991500 |
| t_003047 | 50.991500 |
| t_008183 | 55.993000 |
| t_004895 | 67.991500 |
| t_001601 | 67.991500 |
| t_006432 | 50.991500 |
| t_001090 | 67.991500 |
| t_007871 | 67.991500 |
| t_005252 | 50.991500 |
| t_004860 | 55.993000 |
| t_006414 | 67.991500 |
| t_005551 | 67.991500 |
| t_005125 | 67.991500 |
| t_000813 | 50.991500 |
| t_006178 | 50.991500 |
| t_003888 | 58.190300 |
| t_005383 | 67.991500 |
| t_001041 | 67.991500 |
| t_003376 | 67.991500 |
| t_003749 | 50.991500 |
| t_000483 | 50.991500 |
| t_004604 | 67.991500 |
| t_004540 | 50.991500 |
| t_001639 | 67.991500 |
| t_007518 | 50.991500 |
| t_001476 | 67.991500 |
| t_002100 | 55.993000 |
| t_006226 | 77.590300 |
| t_003602 | 77.590300 |
| t_003499 | 67.991500 |
| t_005569 | 77.590300 |
| t_001699 | 67.991500 |
| t_004667 | 67.991500 |
| t_002179 | 50.991500 |
| t_003911 | 50.991500 |
| t_006483 | 67.991500 |
| t_005071 | 50.991500 |
| t_001452 | 67.991500 |
| t_003706 | 67.991500 |
| t_004230 | 67.991500 |
| t_005660 | 50.991500 |
| t_001893 | 67.991500 |
| t_001249 | 77.590300 |
| t_003360 | 50.991500 |
| t_000754 | 67.991500 |
| t_005041 | 55.993000 |
| t_004223 | 67.991500 |
| t_004198 | 50.991500 |
| t_007542 | 67.991500 |
| t_002890 | 55.993000 |
| t_001587 | 55.993000 |
| t_005179 | 67.991500 |
| t_007533 | 67.991500 |
| t_002463 | 67.991500 |
| t_006158 | 67.991500 |
And this one, with the alias in HAVING?
Guess the result first, then run the query. Fix the query, then Check.
Output columns: country, n
Tables, columns and how they connect
transactions — one row = one paid (or trial) period of a subscription
country— customer's country
| country |
|---|
| BR |
| BR |
| BR |
"Today" is 2026-09-30 00:00 UTC. All times are UTC. Every run is rolled back, so you cannot break the data.
SELECT country, COUNT(*) AS n FROM transactions GROUP BY country HAVING n > 1000;
Show answer
No: column "n" does not exist. In PostgreSQL, HAVING needs the expression itself: HAVING COUNT(*) > 1000. In ORDER BY the alias is fine, because sorting happens after SELECT.
This is what PostgreSQL returns for the query as it is:
Show the fix
SELECT country, COUNT(*) AS nFROM transactionsGROUP BY countryHAVING COUNT(*) > 1000;| country | n |
|---|---|
| US | 2753 |
ORDER BY runs after SELECT, so it sees aliases. PostgreSQL also accepts an alias or a position in GROUP BY. This is a convenience of the dialect; it does not reach WHERE or HAVING.
SELECT channel AS s, COUNT(*) AS nFROM transactionsGROUP BY sORDER BY n DESC;| s | n |
|---|---|
| north_market | 4594 |
| south_market | 2855 |
| web | 740 |
| promo | 105 |
WHERE or HAVING
Section titled “WHERE or HAVING”A condition on single rows goes in WHERE: test purchases, dates, channel. A condition on a group’s aggregate goes in HAVING: “more than 300 transactions”. Products with at least 15 refunds, test purchases excluded:
SELECT product_id, COUNT(*) AS refundsFROM transactionsWHERE NOT is_test AND refunded_at IS NOT NULLGROUP BY product_idHAVING COUNT(*) >= 15ORDER BY refunds DESC, product_id;| product_id | refunds |
|---|---|
| prd_08 | 17 |
| prd_20 | 17 |
| prd_04 | 16 |
HAVING channel = 'web' also runs. But it groups every channel first and then throws most groups away. If a condition does not use an aggregate, put it in WHERE.
Three kinds of COUNT
Section titled “Three kinds of COUNT”COUNT(*)counts rows.COUNT(col)counts rows wherecolis not NULL.COUNT(DISTINCT col)counts different non-NULL values.
What is the difference between the three counters?
Guess the result first, then run the query.
Tables, columns and how they connect
transactions — one row = one paid (or trial) period of a subscription
channel— north_market / south_market (partner marketplaces) / web (own checkout) / promo (free access, price 0)refunded_at— when the money was returned; NULL = no refund; "refunded" = refunded_at IS NOT NULLis_test— test purchase: exclude it from business numbers
| channel | refunded_at | is_test |
|---|---|---|
| north_market | NULL | false |
| north_market | NULL | false |
| north_market | 2025-02-04 15:18:13 | false |
"Today" is 2026-09-30 00:00 UTC. All times are UTC. Every run is rolled back, so you cannot break the data.
SELECT COUNT(*) AS all_rows,
COUNT(refunded_at) AS refunded,
COUNT(DISTINCT channel) AS channels
FROM transactions
WHERE NOT is_test;Show answer
8032 rows, 180 of them with a refund, 4 channels. COUNT(*) counts rows, COUNT(column) counts rows where the column is not NULL, and COUNT(DISTINCT column) counts different values.
This is what PostgreSQL returns for the query as it is:
| all_rows | refunded | channels |
|---|---|---|
| 8032 | 180 | 4 |
A customer can buy many times. “How many customers” is COUNT(DISTINCT customer_id), not COUNT(*).
Georgia, September, no test purchases: transactions and customers. Why are the numbers different?
Guess the result first, then run the query.
Tables, columns and how they connect
transactions — one row = one paid (or trial) period of a subscription
customer_id— the customerstart_time— start of the period = time of purchase; "started in …" means this columnis_test— test purchase: exclude it from business numberscountry— customer's country
| customer_id | start_time | is_test | country |
|---|---|---|---|
| cus_00001 | 2025-10-12 16:30:29 | false | GE |
| cus_00002 | 2025-06-25 19:26:50 | false | US |
| cus_00003 | 2025-02-27 08:20:21 | false | BR |
"Today" is 2026-09-30 00:00 UTC. All times are UTC. Every run is rolled back, so you cannot break the data.
SELECT COUNT(*) AS transactions,
COUNT(DISTINCT customer_id) AS customers
FROM transactions
WHERE country = 'GE'
AND NOT is_test
AND start_time >= '2026-09-01' AND start_time < '2026-10-01';Show answer
39 transactions and 35 customers: some customers paid more than once in the month. “How many customers” is COUNT(DISTINCT customer_id). Before you count, ask who the customer is: a person across all products, or a customer of one product.
This is what PostgreSQL returns for the query as it is:
| transactions | customers |
|---|---|
| 39 | 35 |
If a customer means a customer of one product, count pairs: COUNT(DISTINCT (customer_id, product_id)). In the practice data each customer_id buys one product only, so both forms give the same number. The question still shows that you thought about it.
Distinct counts do not add up
Section titled “Distinct counts do not add up”A customer who paid in June and in July is one customer in each month:
SELECT CAST(date_trunc('month', start_time) AS DATE) AS month, COUNT(DISTINCT customer_id) AS customersFROM transactionsWHERE NOT is_trial AND NOT is_test AND channel <> 'promo' AND start_time >= TIMESTAMP '2026-06-01' AND start_time < TIMESTAMP '2026-09-01'GROUP BY 1ORDER BY 1;| month | customers |
|---|---|
| 2026-06-01 | 393 |
| 2026-07-01 | 399 |
| 2026-08-01 | 432 |
The three months add up to 1224, but the same filter without GROUP BY returns 691 different customers. For the whole quarter, count distinct values over the quarter. Never add up distinct counts of smaller groups.
Ties in ORDER BY
Section titled “Ties in ORDER BY”With ORDER BY gross_usd DESC alone, two equal sums come out in any order, and LIMIT may cut the wrong one. Add a second key: ORDER BY gross_usd DESC, channel. DESC applies only to the column right before it, so ORDER BY paid_at DESC, payout_id sorts payout_id in ascending order.
Practice
Section titled “Practice”Gross revenue (charged_usd) per channel for August 2026, test purchases excluded. Highest first.
Output columns: channel, gross_usdOrder: ORDER BY gross_usd DESC, channel
Tables, columns and how they connect
transactions — one row = one paid (or trial) period of a subscription
channel— north_market / south_market (partner marketplaces) / web (own checkout) / promo (free access, price 0)start_time— start of the period = time of purchase; "started in …" means this columncharged_usd— what the customer paid (gross)is_test— test purchase: exclude it from business numbers
| channel | start_time | charged_usd | is_test |
|---|---|---|---|
| north_market | 2025-01-01 04:48:03 | 79.99 | false |
| north_market | 2025-01-01 06:59:58 | 6.99 | false |
| north_market | 2025-01-01 02:08:33 | 6.99 | false |
"Today" is 2026-09-30 00:00 UTC. All times are UTC. Every run is rolled back, so you cannot break the data.
-- your query here
Show answer
Reference
SELECT channel, SUM(charged_usd) AS gross_usdFROM transactionsWHERE NOT is_test AND start_time >= TIMESTAMP '2026-08-01' AND start_time < TIMESTAMP '2026-09-01'GROUP BY channelORDER BY gross_usd DESC, channel;Expected output
| channel | gross_usd |
|---|---|
| north_market | 4079.18 |
| south_market | 2600.41 |
| web | 518.56 |
| promo | 0.00 |
One row per channel: GROUP BY channel. The second sort key (channel) settles equal sums. The promo row stays in the result with 0.00: promo transactions are real rows, and the report shows them honestly.
Countries with more than 300 paid transactions that started in January–September 2026. Country and count, biggest first.
Output columns: country, paid_transactionsOrder: ORDER BY paid_transactions DESC, country
Tables, columns and how they connect
transactions — one row = one paid (or trial) period of a subscription
channel— north_market / south_market (partner marketplaces) / web (own checkout) / promo (free access, price 0)is_trial— free trial (7 days, price 0)start_time— start of the period = time of purchase; "started in …" means this columnis_test— test purchase: exclude it from business numberscountry— customer's country
| channel | is_trial | start_time | is_test | country |
|---|---|---|---|---|
| north_market | false | 2025-01-01 04:48:03 | false | IN |
| north_market | false | 2025-01-01 06:59:58 | false | US |
| north_market | false | 2025-01-01 02:08:33 | false | IN |
"Today" is 2026-09-30 00:00 UTC. All times are UTC. Every run is rolled back, so you cannot break the data.
-- your query here
Show answer
Reference
SELECT country, COUNT(*) AS paid_transactionsFROM transactionsWHERE NOT is_trial AND NOT is_test AND channel <> 'promo' AND start_time >= TIMESTAMP '2026-01-01' AND start_time < TIMESTAMP '2026-10-01'GROUP BY countryHAVING COUNT(*) > 300ORDER BY paid_transactions DESC, country;Expected output
| country | paid_transactions |
|---|---|
| US | 1201 |
| IN | 459 |
| DE | 440 |
| BR | 439 |
| GE | 438 |
| JP | 425 |
| GB | 328 |
WHERE keeps the paid rows of nine months before grouping; HAVING keeps the countries after it. In HAVING, write the expression COUNT(*) itself: PostgreSQL does not see the alias there.
How many distinct paying customers (customer_id) per channel in September 2026? Paid transactions only.
Output columns: channel, customersOrder: ORDER BY channel
Tables, columns and how they connect
transactions — one row = one paid (or trial) period of a subscription
customer_id— the customerchannel— north_market / south_market (partner marketplaces) / web (own checkout) / promo (free access, price 0)is_trial— free trial (7 days, price 0)start_time— start of the period = time of purchase; "started in …" means this columnis_test— test purchase: exclude it from business numbers
| customer_id | channel | is_trial | start_time | is_test |
|---|---|---|---|---|
| cus_00001 | south_market | false | 2025-10-12 16:30:29 | false |
| cus_00002 | south_market | false | 2025-06-25 19:26:50 | false |
| cus_00003 | south_market | false | 2025-02-27 08:20:21 | false |
"Today" is 2026-09-30 00:00 UTC. All times are UTC. Every run is rolled back, so you cannot break the data.
-- your query here
Show answer
Reference
SELECT channel, COUNT(DISTINCT customer_id) AS customersFROM transactionsWHERE NOT is_trial AND NOT is_test AND channel <> 'promo' AND start_time >= TIMESTAMP '2026-09-01' AND start_time < TIMESTAMP '2026-10-01'GROUP BY channelORDER BY channel;Expected output
| channel | customers |
|---|---|
| north_market | 203 |
| south_market | 126 |
| web | 45 |
A customer can buy several times in a month, so this is COUNT(DISTINCT customer_id). Say out loud who the customer is: a person across all products, or a customer of one product.
ARPPU for September 2026 per channel: net revenue (revenue_usd) of paid transactions divided by distinct paying customers, 2 decimals. Paid means not a trial, not a test purchase, not promo; refunded transactions stay in (their revenue_usd is 0).
Output columns: channel, arppu_usdOrder: ORDER BY channel
Tables, columns and how they connect
transactions — one row = one paid (or trial) period of a subscription
customer_id— the customerchannel— north_market / south_market (partner marketplaces) / web (own checkout) / promo (free access, price 0)is_trial— free trial (7 days, price 0)start_time— start of the period = time of purchase; "started in …" means this columnrevenue_usd— revenue net of refunds: 0 if the transaction was refunded (net)is_test— test purchase: exclude it from business numbers
| customer_id | channel | is_trial | start_time | revenue_usd | is_test |
|---|---|---|---|---|---|
| cus_00001 | south_market | false | 2025-10-12 16:30:29 | 79.99 | false |
| cus_00002 | south_market | false | 2025-06-25 19:26:50 | 2.99 | false |
| cus_00003 | south_market | false | 2025-02-27 08:20:21 | 4.99 | false |
"Today" is 2026-09-30 00:00 UTC. All times are UTC. Every run is rolled back, so you cannot break the data.
-- your query here
Show answer
Reference
SELECT channel, ROUND(SUM(revenue_usd) / COUNT(DISTINCT customer_id), 2) AS arppu_usdFROM transactionsWHERE NOT is_trial AND NOT is_test AND channel <> 'promo' AND start_time >= TIMESTAMP '2026-09-01' AND start_time < TIMESTAMP '2026-10-01'GROUP BY channelORDER BY channel;Expected output
| channel | arppu_usd |
|---|---|
| north_market | 14.53 |
| south_market | 17.98 |
| web | 16.61 |
ARPPU is the average revenue per paying user, here per paying customer: SUM(revenue_usd) / COUNT(DISTINCT customer_id). revenue_usd is numeric, so the division keeps its decimals. If both sides were integers, you would need 1.0 * in front. ROUND comes last, on the final value.
Further reading
Section titled “Further reading”- GROUP BY and HAVING clauses — groups, and conditions on groups.
- SELECT — the description starts with the numbered order in which a query is processed.
- GROUP BY in SELECT — output column names and positions, and grouping by a primary key.
- Aggregate expressions —
COUNT(*),DISTINCTandFILTERinside an aggregate. - Aggregate functions — the full list.
Related topics
Section titled “Related topics”- Filters and dates — what goes into
WHEREbefore any grouping. - NULL logic — why
COUNT(col)skips rows and why an emptySUMis NULL. - Conditional aggregation — several counters in one
GROUP BY. - Duplicates and idempotency —
COUNT(*)againstCOUNT(DISTINCT id)when events arrive twice. - Top N per group — when you need the best row in each group, not a summary.
Site content: CC BY 4.0. Code: MIT. The exercises run in your browser: PostgreSQL by PGlite, Python by Pyodide.