Skip to content

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.

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 transactions
FROM transactions
WHERE 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_period
ORDER BY channel, plan_period;
channelplan_periodtransactions
promoP1M6
promoP1Y2
webP1M37
webP1W6
webP1Y8

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.

SQLTrap: what will it return?

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
channelcountry
north_marketIN
north_marketUS
north_marketIN

"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:

Error
column "transactions.channel" must appear in the GROUP BY clause or be used in an aggregate function
Show the fix
SELECT country, channel, COUNT(*) AS n
FROM transactions
GROUP BY country, channel;
countrychanneln
GBsouth_market284
GEnorth_market520
GBpromo5
USsouth_market927
USpromo67
USweb261
BRpromo4
INnorth_market567
BRnorth_market518
JPnorth_market504
BRweb93
GBnorth_market439
DEnorth_market548
GEsouth_market341
INpromo2
GBweb96
DEpromo5
DEsouth_market283
USnorth_market1498
GEweb90
GEpromo8
JPpromo14
INweb81
DEweb69
JPweb50
JPsouth_market335
INsouth_market310
BRsouth_market375
28 rows

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.

A query is written in one order and runs in another:

StepClauseWhat it works with
1FROM, JOINthe rows of the tables
2WHEREone row at a time
3GROUP BYrows that become groups
4HAVINGone group at a time, with its aggregates
5SELECToutput columns; aliases are born here
6ORDER BYthe output, aliases included
7LIMITthe sorted output

An alias is created in step 5, so WHERE and HAVING cannot see it yet.

SQLTrap: what will it return?core

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 transaction
  • revenue_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_idrevenue_usdfee_rate
t_00000179.990.1500
t_0000022.990.1500
t_0000034.990.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:

Error
column "proceeds" does not exist
Show the fix
WITH t AS (
SELECT transaction_id,
revenue_usd * (1 - fee_rate) AS proceeds
FROM transactions
)
SELECT transaction_id, proceeds
FROM t
WHERE proceeds > 50;
transaction_idproceeds
t_00493555.993000
t_00647467.991500
t_00452267.991500
t_00211150.991500
t_00087750.991500
t_00376367.991500
t_00407767.991500
t_00654767.991500
t_00449367.991500
t_00700267.991500
t_00244077.590300
t_00535767.991500
t_00253967.991500
t_00467355.993000
t_00801050.991500
t_00312650.991500
t_00214267.991500
t_00162167.991500
t_00190950.991500
t_00032367.991500
t_00096667.991500
t_00755650.991500
t_00355067.991500
t_00821567.991500
t_00368177.590300
t_00077467.991500
t_00062567.991500
t_00828255.993000
t_00482950.991500
t_00628367.991500
t_00046667.991500
t_00169650.991500
t_00554667.991500
t_00498867.991500
t_00539167.991500
t_00338267.991500
t_00454250.991500
t_00061967.991500
t_00647267.991500
t_00589458.190300
t_00235967.991500
t_00580867.991500
t_00413777.590300
t_00244567.991500
t_00054050.991500
t_00489067.991500
t_00304750.991500
t_00818355.993000
t_00489567.991500
t_00160167.991500
t_00643250.991500
t_00109067.991500
t_00787167.991500
t_00525250.991500
t_00486055.993000
t_00641467.991500
t_00555167.991500
t_00512567.991500
t_00081350.991500
t_00617850.991500
t_00388858.190300
t_00538367.991500
t_00104167.991500
t_00337667.991500
t_00374950.991500
t_00048350.991500
t_00460467.991500
t_00454050.991500
t_00163967.991500
t_00751850.991500
t_00147667.991500
t_00210055.993000
t_00622677.590300
t_00360277.590300
t_00349967.991500
t_00556977.590300
t_00169967.991500
t_00466767.991500
t_00217950.991500
t_00391150.991500
t_00648367.991500
t_00507150.991500
t_00145267.991500
t_00370667.991500
t_00423067.991500
t_00566050.991500
t_00189367.991500
t_00124977.590300
t_00336050.991500
t_00075467.991500
t_00504155.993000
t_00422367.991500
t_00419850.991500
t_00754267.991500
t_00289055.993000
t_00158755.993000
t_00517967.991500
t_00753367.991500
t_00246367.991500
t_00615867.991500
493 rows (first 100 shown)
SQLTrap: what will it return?

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:

Error
column "n" does not exist
Show the fix
SELECT country, COUNT(*) AS n
FROM transactions
GROUP BY country
HAVING COUNT(*) > 1000;
countryn
US2753
1 row

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 n
FROM transactions
GROUP BY s
ORDER BY n DESC;
sn
north_market4594
south_market2855
web740
promo105

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 refunds
FROM transactions
WHERE NOT is_test
AND refunded_at IS NOT NULL
GROUP BY product_id
HAVING COUNT(*) >= 15
ORDER BY refunds DESC, product_id;
product_idrefunds
prd_0817
prd_2017
prd_0416

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.

  • COUNT(*) counts rows.
  • COUNT(col) counts rows where col is not NULL.
  • COUNT(DISTINCT col) counts different non-NULL values.
SQLTrap: what will it return?

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 NULL
  • is_test — test purchase: exclude it from business numbers
channelrefunded_atis_test
north_marketNULLfalse
north_marketNULLfalse
north_market2025-02-04 15:18:13false

"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_rowsrefundedchannels
80321804

A customer can buy many times. “How many customers” is COUNT(DISTINCT customer_id), not COUNT(*).

SQLTrap: what will it return?

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 customer
  • start_time — start of the period = time of purchase; "started in …" means this column
  • is_test — test purchase: exclude it from business numbers
  • country — customer's country
customer_idstart_timeis_testcountry
cus_000012025-10-12 16:30:29falseGE
cus_000022025-06-25 19:26:50falseUS
cus_000032025-02-27 08:20:21falseBR

"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:

transactionscustomers
3935

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.

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 customers
FROM transactions
WHERE 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 1
ORDER BY 1;
monthcustomers
2026-06-01393
2026-07-01399
2026-08-01432

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.

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.

SQLWrite a querycore

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 column
  • charged_usd — what the customer paid (gross)
  • is_test — test purchase: exclude it from business numbers
channelstart_timecharged_usdis_test
north_market2025-01-01 04:48:0379.99false
north_market2025-01-01 06:59:586.99false
north_market2025-01-01 02:08:336.99false

"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_usd
FROM transactions
WHERE NOT is_test
AND start_time >= TIMESTAMP '2026-08-01'
AND start_time < TIMESTAMP '2026-09-01'
GROUP BY channel
ORDER BY gross_usd DESC, channel;

Expected output

channelgross_usd
north_market4079.18
south_market2600.41
web518.56
promo0.00
4 rows

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.

SQLWrite a querycore

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 column
  • is_test — test purchase: exclude it from business numbers
  • country — customer's country
channelis_trialstart_timeis_testcountry
north_marketfalse2025-01-01 04:48:03falseIN
north_marketfalse2025-01-01 06:59:58falseUS
north_marketfalse2025-01-01 02:08:33falseIN

"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_transactions
FROM transactions
WHERE 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 country
HAVING COUNT(*) > 300
ORDER BY paid_transactions DESC, country;

Expected output

countrypaid_transactions
US1201
IN459
DE440
BR439
GE438
JP425
GB328
7 rows

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.

SQLWrite a querycore

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 customer
  • 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 column
  • is_test — test purchase: exclude it from business numbers
customer_idchannelis_trialstart_timeis_test
cus_00001south_marketfalse2025-10-12 16:30:29false
cus_00002south_marketfalse2025-06-25 19:26:50false
cus_00003south_marketfalse2025-02-27 08:20:21false

"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 customers
FROM transactions
WHERE 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 channel
ORDER BY channel;

Expected output

channelcustomers
north_market203
south_market126
web45
3 rows

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.

SQLWrite a query

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 customer
  • 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 column
  • revenue_usd — revenue net of refunds: 0 if the transaction was refunded (net)
  • is_test — test purchase: exclude it from business numbers
customer_idchannelis_trialstart_timerevenue_usdis_test
cus_00001south_marketfalse2025-10-12 16:30:2979.99false
cus_00002south_marketfalse2025-06-25 19:26:502.99false
cus_00003south_marketfalse2025-02-27 08:20:214.99false

"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_usd
FROM transactions
WHERE 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 channel
ORDER BY channel;

Expected output

channelarppu_usd
north_market14.53
south_market17.98
web16.61
3 rows

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.

Site content: CC BY 4.0. Code: MIT. The exercises run in your browser: PostgreSQL by PGlite, Python by Pyodide.