Conditional aggregation
Many tasks want several numbers per group: all transactions, trials, refunds and a refund rate. One GROUP BY with conditional aggregates computes them in a single pass over the table. The typical bugs are a rate of 0 from integer division and an average pulled down by zeros.
CASE: a label for each row
Section titled “CASE: a label for each row”CASE checks its branches from top to bottom and returns the first one that is true. Without ELSE, a row that matches nothing gets NULL. Group by the label to count the rows in each bucket:
SELECT CASE WHEN is_trial THEN 'trial' WHEN channel = 'promo' THEN 'promo' ELSE 'paid' END AS kind, COUNT(*) AS transactionsFROM transactionsWHERE NOT is_test AND start_time >= TIMESTAMP '2026-07-01' AND start_time < TIMESTAMP '2026-08-01'GROUP BY 1ORDER BY 1;| kind | transactions |
|---|---|
| paid | 427 |
| promo | 8 |
| trial | 51 |
The order of branches matters when a row can match two of them. A trial granted as promo access would be labelled trial here, because that branch comes first. The practice data has no such rows, but say the order out loud anyway.
GROUP BY 1 groups by the first column of SELECT, so the long CASE is written only once.
FILTER: several counters in one pass
Section titled “FILTER: several counters in one pass”COUNT(*) FILTER (WHERE …) counts only the rows that pass its condition. Any aggregate accepts a FILTER: SUM(x) FILTER (…), AVG(x) FILTER (…). The same counter has two portable forms:
SELECT COUNT(*) FILTER (WHERE is_trial) AS with_filter, SUM(CASE WHEN is_trial THEN 1 ELSE 0 END) AS with_sum_case, COUNT(CASE WHEN is_trial THEN 1 END) AS with_count_caseFROM transactionsWHERE NOT is_test;| with_filter | with_sum_case | with_count_case |
|---|---|---|
| 906 | 906 | 906 |
FILTER works in PostgreSQL, SQLite and DuckDB. In MySQL or SQL Server, write SUM(CASE …). COUNT(CASE WHEN … THEN 1 END) also works, because COUNT skips the NULL that CASE returns without ELSE.
Several counters in one SELECT read the table once. Three separate queries joined together read it three times and add three chances to get a filter wrong.
Rates without integer division
Section titled “Rates without integer division”COUNT returns a bigint. In PostgreSQL, an integer divided by an integer is an integer, and the fraction is cut off:
SELECT 7 / 2 AS int_div, 7.0 / 2 AS numeric_div, 1.0 * 7 / 2 AS times_one, 7 / NULLIF(0, 0) AS by_zero;| int_div | numeric_div | times_one | by_zero |
|---|---|---|---|
| 3 | 3.5000000000000000 | 3.5000000000000000 | NULL |
Make one side numeric before you divide: 1.0 * a / b or a::numeric / b. Protect an empty group with NULLIF(b, 0): the rate becomes NULL instead of a division by zero error.
The share of trials. What will share_a and pct_b contain?
Guess the result first, then run the query. Fix the query, then Check.
Output columns: share_a, pct_b
Tables, columns and how they connect
transactions — one row = one paid (or trial) period of a subscription
is_trial— free trial (7 days, price 0)is_test— test purchase: exclude it from business numbers
| is_trial | is_test |
|---|---|
| false | false |
| false | false |
| false | 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(*) FILTER (WHERE is_trial) / COUNT(*) AS share_a,
ROUND(100.0 * COUNT(*) FILTER (WHERE is_trial) / COUNT(*), 1) AS pct_b
FROM transactions
WHERE NOT is_test;Show answer
share_a is 0: COUNT is an integer, and an integer divided by an integer drops the fraction. pct_b is 11.3, because 100.0 makes the expression numeric. Write 1.0 * a / b or a::numeric / b, and add NULLIF(b, 0) against division by zero.
This is what PostgreSQL returns for the query as it is:
| share_a | pct_b |
|---|---|
| 0 | 11.3 |
Show the fix
SELECT ROUND(1.0 * COUNT(*) FILTER (WHERE is_trial) / COUNT(*), 3) AS share_a, ROUND(100.0 * COUNT(*) FILTER (WHERE is_trial) / COUNT(*), 1) AS pct_bFROM transactionsWHERE NOT is_test;| share_a | pct_b |
|---|---|
| 0.113 | 11.3 |
Round once, at the end. Ask what the interviewer wants to see: a share (0.035) or a percentage (3.5).
AVG and the ELSE 0 trap
Section titled “AVG and the ELSE 0 trap”AVG skips NULL. CASE without ELSE returns NULL for the other rows, so AVG(CASE WHEN channel = 'web' THEN charged_usd END) averages the web checkout rows only. ELSE 0 puts a zero for every other row into the average.
The average paid web checkout purchase (trials left out), computed three ways. Which one is wrong?
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)is_trial— free trial (7 days, price 0)charged_usd— what the customer paid (gross)is_test— test purchase: exclude it from business numbers
| channel | is_trial | charged_usd | is_test |
|---|---|---|---|
| north_market | false | 79.99 | false |
| north_market | false | 6.99 | false |
| north_market | false | 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.
SELECT ROUND(AVG(charged_usd) FILTER (WHERE channel = 'web'), 2) AS a_filter,
ROUND(AVG(CASE WHEN channel = 'web' THEN charged_usd END), 2) AS b_case,
ROUND(AVG(CASE WHEN channel = 'web' THEN charged_usd ELSE 0 END), 2) AS c_case_else_0
FROM transactions
WHERE NOT is_test
AND NOT is_trial;Show answer
c is wrong: 1.18 instead of 13.19. With ELSE 0, a zero for every row of the other channels goes into the average. Free trials would do the same: each costs 0.00, which is why WHERE leaves them out. For AVG, use FILTER or CASE without ELSE: NULL does not take part in AVG. For a share, ELSE 0 is exactly what you need: AVG(CASE WHEN … THEN 1.0 ELSE 0 END).
This is what PostgreSQL returns for the query as it is:
| a_filter | b_case | c_case_else_0 |
|---|---|---|
| 13.19 | 13.19 | 1.18 |
For a share, every row must count: matching rows as 1, the others as 0.
SELECT ROUND(AVG(CASE WHEN is_trial THEN 1.0 ELSE 0 END), 3) AS trial_shareFROM transactionsWHERE NOT is_test;| trial_share |
|---|
| 0.113 |
This equals the fixed share_a in the trap above: trials are 11.3% of the rows without test purchases.
Median and percentiles
Section titled “Median and percentiles”A few expensive purchases pull an average up. A median is the middle value, and rare large values do not move it. PostgreSQL computes it with an ordered-set aggregate:
SELECT channel, ROUND(AVG(charged_usd), 2) AS avg_usd, ROUND(CAST(PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY charged_usd) AS numeric), 2) AS median_usdFROM transactionsWHERE NOT is_trial AND NOT is_test AND channel <> 'promo'GROUP BY channelORDER BY channel;| channel | avg_usd | median_usd |
|---|---|---|
| north_market | 14.91 | 7.99 |
| south_market | 15.37 | 7.99 |
| web | 13.19 | 7.99 |
Every channel has a median of 7.99, while the averages are between 13 and 16: a smaller number of annual plans pulls them up.
- The syntax is
PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY x); the 90th percentile is0.9. It works withGROUP BYlike any other aggregate. PERCENTILE_CONTinterpolates between neighbours;PERCENTILE_DISCreturns a value that exists in the data.- It returns
double precision, soROUND(…, 2)without a cast fails withfunction round(double precision, integer) does not exist. - It is not a window function.
OVER (PARTITION BY …)fails withOVER is not supported for ordered-set aggregate percentile_cont. Compute it withGROUP BY, and join the result back if every row needs it.
SELECT PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY x) AS cont, PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY x) AS discFROM (VALUES (1), (2), (3), (10)) AS v(x);| cont | disc |
|---|---|
| 2.5 | 2 |
Practice
Section titled “Practice”Paid transactions that started in September 2026 in three price buckets: 'under 5', '5 to 20', 'over 20' (charged_usd; 5 and 20 go to '5 to 20'). Count per bucket.
Output columns: bucket, transactions
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 columncharged_usd— what the customer paid (gross)is_test— test purchase: exclude it from business numbers
| channel | is_trial | start_time | charged_usd | is_test |
|---|---|---|---|---|
| north_market | false | 2025-01-01 04:48:03 | 79.99 | false |
| north_market | false | 2025-01-01 06:59:58 | 6.99 | false |
| north_market | false | 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 CASE WHEN charged_usd < 5 THEN 'under 5' WHEN charged_usd <= 20 THEN '5 to 20' ELSE 'over 20' END AS bucket, COUNT(*) AS transactionsFROM 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 1;Expected output
| bucket | transactions |
|---|---|
| under 5 | 118 |
| over 20 | 66 |
| 5 to 20 | 244 |
CASE checks the branches from top to bottom and takes the first true one. So the second branch is simply <= 20: everything under 5 was caught above. The hidden data has sales of exactly 5.00 and 20.00, so <= 5 in the first branch or < 20 in the second fails Check. GROUP BY 1 groups by the first column of SELECT. Row order is not checked here.
One row per channel for September 2026, test purchases excluded: all transactions, trials, refunded transactions.
Output columns: channel, transactions, trials, refundedOrder: ORDER BY 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)is_trial— free trial (7 days, price 0)start_time— start of the period = time of purchase; "started in …" means this columnrefunded_at— when the money was returned; NULL = no refund; "refunded" = refunded_at IS NOT NULLis_test— test purchase: exclude it from business numbers
| channel | is_trial | start_time | refunded_at | is_test |
|---|---|---|---|---|
| north_market | false | 2025-01-01 04:48:03 | NULL | false |
| north_market | false | 2025-01-01 02:08:33 | NULL | false |
| north_market | false | 2025-01-22 14:37:00 | 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.
-- your query here
Show answer
Reference
SELECT channel, COUNT(*) AS transactions, COUNT(*) FILTER (WHERE is_trial) AS trials, COUNT(*) FILTER (WHERE refunded_at IS NOT NULL) AS refundedFROM transactionsWHERE NOT is_test AND start_time >= TIMESTAMP '2026-09-01' AND start_time < TIMESTAMP '2026-10-01'GROUP BY channelORDER BY channel;Expected output
| channel | transactions | trials | refunded |
|---|---|---|---|
| north_market | 254 | 16 | 5 |
| promo | 3 | 0 | 0 |
| south_market | 151 | 10 | 3 |
| web | 55 | 6 | 1 |
Several counters in one grouping: COUNT(*) FILTER (WHERE …). The portable form is SUM(CASE WHEN … THEN 1 ELSE 0 END). Three separate queries and a join are not needed.
Refund rate per channel for paid transactions that started in January–August 2026: refunded / all paid, 3 decimals. Highest first.
Output columns: channel, refund_rateOrder: ORDER BY refund_rate 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)is_trial— free trial (7 days, price 0)start_time— start of the period = time of purchase; "started in …" means this columnrefunded_at— when the money was returned; NULL = no refund; "refunded" = refunded_at IS NOT NULLis_test— test purchase: exclude it from business numbers
| channel | is_trial | start_time | refunded_at | is_test |
|---|---|---|---|---|
| north_market | false | 2025-01-01 04:48:03 | NULL | false |
| north_market | false | 2025-01-01 02:08:33 | NULL | false |
| north_market | false | 2025-01-22 14:37:00 | 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.
-- your query here
Show answer
Reference
SELECT channel, ROUND(1.0 * COUNT(*) FILTER (WHERE refunded_at IS NOT NULL) / COUNT(*), 3) AS refund_rateFROM transactionsWHERE NOT is_trial AND NOT is_test AND channel <> 'promo' AND start_time >= TIMESTAMP '2026-01-01' AND start_time < TIMESTAMP '2026-09-01'GROUP BY channelORDER BY refund_rate DESC, channel;Expected output
| channel | refund_rate |
|---|---|
| web | 0.035 |
| north_market | 0.025 |
| south_market | 0.023 |
COUNT is an integer, and an integer divided by an integer in PostgreSQL would give 0 here. You need 1.0 * or ::numeric. September is left out on purpose: refunds arrive up to three weeks after the purchase, so the last month is not complete yet.
Median and 90th percentile purchase price of paid transactions per plan_period, 2 decimals.
Output columns: plan_period, median_usd, p90_usdOrder: ORDER BY plan_period
Tables, columns and how they connect
transactions — one row = one paid (or trial) period of a subscription
plan_period— P1W / P1M / P1Ychannel— north_market / south_market (partner marketplaces) / web (own checkout) / promo (free access, price 0)is_trial— free trial (7 days, price 0)charged_usd— what the customer paid (gross)is_test— test purchase: exclude it from business numbers
| plan_period | channel | is_trial | charged_usd | is_test |
|---|---|---|---|---|
| P1M | north_market | false | 6.99 | false |
| P1M | north_market | false | 6.99 | false |
| P1M | north_market | false | 9.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 plan_period, ROUND(CAST(PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY charged_usd) AS numeric), 2) AS median_usd, ROUND(CAST(PERCENTILE_CONT(0.9) WITHIN GROUP (ORDER BY charged_usd) AS numeric), 2) AS p90_usdFROM transactionsWHERE NOT is_trial AND NOT is_test AND channel <> 'promo'GROUP BY plan_periodORDER BY plan_period;Expected output
| plan_period | median_usd | p90_usd |
|---|---|---|
| P1M | 7.99 | 12.99 |
| P1W | 2.99 | 2.99 |
| P1Y | 49.99 | 79.99 |
Median and percentiles: PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY x); p90 is 0.9, p95 is 0.95. The result is double precision, so cast it to numeric for ROUND with two decimals. Every weekly plan costs 2.99, so both P1W percentiles are equal.
Further reading
Section titled “Further reading”- CASE — searched and simple forms, and what happens without
ELSE. - Aggregate expressions — the
FILTERclause andWITHIN GROUP. - Ordered-set aggregate functions —
percentile_cont,percentile_discandmode. - Mathematical operators — integer division truncates;
roundwith decimal places takesnumeric. - NULLIF — the guard against division by zero.
Related topics
Section titled “Related topics”- Grouping and counting — the
GROUP BYthat conditional aggregates live in. - NULL logic — why
CASEwithoutELSEworks inAVGand why an emptySUMis NULL. - Shares and running totals — a share of the total with a window function.
- Money and ledgers — signed sums and rounding money.
- Funnels and churn — interview tasks built from several counters and rates.
Site content: CC BY 4.0. Code: MIT. The exercises run in your browser: PostgreSQL by PGlite, Python by Pyodide.