Skip to content

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 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 transactions
FROM transactions
WHERE NOT is_test
AND start_time >= TIMESTAMP '2026-07-01'
AND start_time < TIMESTAMP '2026-08-01'
GROUP BY 1
ORDER BY 1;
kindtransactions
paid427
promo8
trial51

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.

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_case
FROM transactions
WHERE NOT is_test;
with_filterwith_sum_casewith_count_case
906906906

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.

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_divnumeric_divtimes_oneby_zero
33.50000000000000003.5000000000000000NULL

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.

SQLTrap: what will it return?core

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_trialis_test
falsefalse
falsefalse
falsefalse

"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_apct_b
011.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_b
FROM transactions
WHERE NOT is_test;
share_apct_b
0.11311.3
1 row

Round once, at the end. Ask what the interviewer wants to see: a share (0.035) or a percentage (3.5).

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.

SQLTrap: what will it return?

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
channelis_trialcharged_usdis_test
north_marketfalse79.99false
north_marketfalse6.99false
north_marketfalse6.99false

"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_filterb_casec_case_else_0
13.1913.191.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_share
FROM transactions
WHERE 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.

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_usd
FROM transactions
WHERE NOT is_trial AND NOT is_test AND channel <> 'promo'
GROUP BY channel
ORDER BY channel;
channelavg_usdmedian_usd
north_market14.917.99
south_market15.377.99
web13.197.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 is 0.9. It works with GROUP BY like any other aggregate.
  • PERCENTILE_CONT interpolates between neighbours; PERCENTILE_DISC returns a value that exists in the data.
  • It returns double precision, so ROUND(…, 2) without a cast fails with function round(double precision, integer) does not exist.
  • It is not a window function. OVER (PARTITION BY …) fails with OVER is not supported for ordered-set aggregate percentile_cont. Compute it with GROUP 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 disc
FROM (VALUES (1), (2), (3), (10)) AS v(x);
contdisc
2.52
SQLWrite a querycore

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 column
  • charged_usd — what the customer paid (gross)
  • is_test — test purchase: exclude it from business numbers
channelis_trialstart_timecharged_usdis_test
north_marketfalse2025-01-01 04:48:0379.99false
north_marketfalse2025-01-01 06:59:586.99false
north_marketfalse2025-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 CASE
WHEN charged_usd < 5 THEN 'under 5'
WHEN charged_usd <= 20 THEN '5 to 20'
ELSE 'over 20'
END AS bucket,
COUNT(*) AS transactions
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 1;

Expected output

buckettransactions
under 5118
over 2066
5 to 20244
3 rows

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.

SQLWrite a querycore

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 column
  • 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
channelis_trialstart_timerefunded_atis_test
north_marketfalse2025-01-01 04:48:03NULLfalse
north_marketfalse2025-01-01 02:08:33NULLfalse
north_marketfalse2025-01-22 14:37:002025-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.

-- 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 refunded
FROM transactions
WHERE NOT is_test
AND start_time >= TIMESTAMP '2026-09-01'
AND start_time < TIMESTAMP '2026-10-01'
GROUP BY channel
ORDER BY channel;

Expected output

channeltransactionstrialsrefunded
north_market254165
promo300
south_market151103
web5561
4 rows

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.

SQLWrite a querycore

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 column
  • 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
channelis_trialstart_timerefunded_atis_test
north_marketfalse2025-01-01 04:48:03NULLfalse
north_marketfalse2025-01-01 02:08:33NULLfalse
north_marketfalse2025-01-22 14:37:002025-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.

-- your query here
Show answer

Reference

SELECT channel,
ROUND(1.0 * COUNT(*) FILTER (WHERE refunded_at IS NOT NULL) / COUNT(*), 3) AS refund_rate
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-09-01'
GROUP BY channel
ORDER BY refund_rate DESC, channel;

Expected output

channelrefund_rate
web0.035
north_market0.025
south_market0.023
3 rows

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.

SQLWrite a query

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 / P1Y
  • 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
plan_periodchannelis_trialcharged_usdis_test
P1Mnorth_marketfalse6.99false
P1Mnorth_marketfalse6.99false
P1Mnorth_marketfalse9.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 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_usd
FROM transactions
WHERE NOT is_trial AND NOT is_test AND channel <> 'promo'
GROUP BY plan_period
ORDER BY plan_period;

Expected output

plan_periodmedian_usdp90_usd
P1M7.9912.99
P1W2.992.99
P1Y49.9979.99
3 rows

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.

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