Skip to content

Conversion and churn

Product metrics come next: the share of trials that converted, a daily revenue line with a running total and a 7-day average, and the share of subscriptions that were not renewed. Each is a few CTEs, a rate without integer division, and a clear answer to “who is in the denominator?”. They build on CTE and EXISTS, CASE, FILTER and rates and Shares and running totals.

SQLQ08 · Difficulty: medium · Target time: 10 min

For trials that started in April–June 2026, show per plan how many trials there were, how many converted to paid, and the conversion rate.

Output columns: plan_id, trials, conversions, conversion_rateOrder: ORDER BY plan_id

Ask first

Say each question out loud before you code. Open the interviewer's answer only after you asked.

  1. How do I know a trial converted?

    The same chain (original_transaction_id) has a transaction with is_trial_conversion = true.

  2. Rate format?

    conversions / trials, rounded to 3 decimals. Watch out for integer division in PostgreSQL.

  3. Test?

    Excluded everywhere.

  4. A trial started in late June and converted in July. Does it count?

    Yes. The start of the trial decides the quarter; the conversion can come later.

About the data: transactions
  • All periods of one subscription form a chain: they share original_transaction_id (for the first row it equals its own id).
  • A trial is a row with is_trial = true. If the customer paid after the trial, the same chain has a row with is_trial_conversion = true.
  • In the example, chain t_000141 is a trial that converted (then a renewal and a refund); t_003269 is a trial that never converted — one row.
  • A product has several plans (plan_id, for example prd_02.monthly and prd_02.annual): the result has one row per plan.

A few rows

SELECT transaction_id AS id, original_transaction_id AS chain,
is_trial AS trial, is_trial_conversion AS conversion, renewal_number AS n,
start_time, end_time, revenue_usd AS net, refunded_at
FROM transactions
WHERE original_transaction_id IN ('t_000141', 't_003269')
ORDER BY chain, start_time;
idchaintrialconversionnstart_timeend_timenetrefunded_at
t_000141t_000141truefalse12025-07-06 17:45:042025-07-13 17:45:040.00NULL
t_000142t_000141falsetrue22025-07-13 17:45:042025-08-13 17:45:044.99NULL
t_000143t_000141falsefalse32025-08-13 17:45:042025-09-13 17:45:044.99NULL
t_000144t_000141falsefalse42025-09-13 17:45:042025-10-13 17:45:040.002025-09-20 20:52:05
t_003269t_003269truefalse12026-02-24 11:20:412026-03-03 11:20:410.00NULL

"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
Hint: what the interviewer would nudge

A trial and its conversion are different rows of one chain. Put the Q2 trials in one CTE and the converted chains in another, then choose the join that keeps trials without a conversion.

Reference solution
WITH trials AS (
SELECT plan_id, original_transaction_id
FROM transactions
WHERE is_trial
AND NOT is_test
AND start_time >= TIMESTAMP '2026-04-01'
AND start_time < TIMESTAMP '2026-07-01'
),
conversions AS (
SELECT DISTINCT original_transaction_id
FROM transactions
WHERE is_trial_conversion
AND NOT is_test
)
SELECT t.plan_id,
COUNT(*) AS trials,
COUNT(c.original_transaction_id) AS conversions,
ROUND(1.0 * COUNT(c.original_transaction_id) / COUNT(*), 3) AS conversion_rate
FROM trials t
LEFT JOIN conversions c USING (original_transaction_id)
GROUP BY t.plan_id
ORDER BY t.plan_id;

Expected output

plan_idtrialsconversionsconversion_rate
prd_01.annual200.000
prd_01.monthly200.000
prd_02.annual300.000
prd_02.monthly520.400
prd_03.annual410.250
prd_03.monthly221.000
prd_04.annual210.500
prd_04.monthly310.333
prd_05.annual310.333
prd_05.monthly540.800
prd_06.annual210.500
prd_06.monthly410.250
prd_07.annual410.250
prd_07.monthly830.375
prd_08.annual331.000
prd_08.monthly320.667
prd_09.annual200.000
prd_09.monthly200.000
prd_10.annual430.750
prd_10.monthly331.000
39 rows (first 20 shown)
WalkthroughTry the task first: the walkthrough is most useful after your own attempt.

What it is for. The share of free trials that turned into a payment: the main number of a trial funnel. The trial and the first payment are different rows of one chain, with the same original_transaction_id.

Steps.

  1. A CTE trials: trials that started in April–June.
  2. A CTE conversions: the chains that have a row with is_trial_conversion.
  3. trials LEFT JOIN conversions: COUNT(*) is the number of trials, COUNT(c.original_transaction_id) the number of conversions, and the rate is 1.0 * conversions / trials.

Traps.

  • An INNER JOIN loses the trials that did not convert, and every rate becomes 1.
  • Integer division gives 0, or 1 when every trial converted.
  • Each chain here has at most one conversion row. DISTINCT in conversions keeps the count right if a chain ever has two.
  • A trial can convert in July. The start of the trial decides the quarter, so do not filter conversions by date. Here 3 trials converted in July.

Check. 39 rows, one per plan. Overall there are 139 trials and 63 conversions, a rate of 0.453. prd_02.monthly: 5 trials, 2 conversions, 0.400.

Follow-up. “Can we trust the number for June?” A trial lasts 7 days, so trials from the last week before “today” have no outcome yet. For Q2 that week is long past, but for a report on the last month it matters: mark that period as incomplete. More follow-ups of this kind are on Database concepts.

In production. A trial reaches its conversion through original_transaction_id, so index that column. It can be a partial index on the side the query looks up: WHERE is_trial_conversion.

Q09. Running revenue and 7-day average per merchant

Section titled “Q09. Running revenue and 7-day average per merchant”
SQLQ09 · Difficulty: medium · Target time: 15 min

For every merchant and every day from 2026-09-01 to 2026-09-29, show the net revenue of that day, the running total since the start of the month, and the average of the last 7 days.

Output columns: merchant_id, day (DATE), net_usd, running_usd, avg_7d_usdOrder: ORDER BY merchant_id, day

Ask first

Say each question out loud before you code. Open the interviewer's answer only after you asked.

  1. Days without revenue?

    Must appear with 0 and count in the average.

  2. 7-day average of what window?

    The current day and the 6 days before it. For the first days of the month, average over the days that exist (no August data). Round to 2 decimals.

  3. Net revenue?

    SUM(revenue_usd) by the day of start_time, test purchases excluded.

About the data: transactions, products, merchants
  • Revenue per day is SUM(revenue_usd) by CAST(start_time AS DATE), test purchases excluded.
  • Every merchant × every day comes from a calendar and a CROSS JOIN; empty days are 0.

"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
Hint: what the interviewer would nudge

Before any window function, build a grid of merchants and days, so that every day has a row. The running total and the 7-day average are then two windows with different frames.

Reference solution
WITH days AS (
SELECT CAST(d AS DATE) AS day
FROM generate_series(TIMESTAMP '2026-09-01', TIMESTAMP '2026-09-29', INTERVAL '1 day') AS g(d)
),
daily AS (
SELECT p.merchant_id,
CAST(t.start_time AS DATE) AS day,
SUM(t.revenue_usd) AS net_usd
FROM transactions t
JOIN products p ON p.id = t.product_id
WHERE NOT t.is_test
AND t.start_time >= TIMESTAMP '2026-09-01'
AND t.start_time < TIMESTAMP '2026-09-30'
GROUP BY 1, 2
),
grid AS (
SELECT m.id AS merchant_id, days.day, COALESCE(daily.net_usd, 0) AS net_usd
FROM merchants m
CROSS JOIN days
LEFT JOIN daily ON daily.merchant_id = m.id AND daily.day = days.day
)
SELECT merchant_id,
day,
net_usd,
SUM(net_usd) OVER (PARTITION BY merchant_id ORDER BY day) AS running_usd,
ROUND(AVG(net_usd) OVER (PARTITION BY merchant_id ORDER BY day
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW), 2) AS avg_7d_usd
FROM grid
ORDER BY merchant_id, day;

Expected output

merchant_iddaynet_usdrunning_usdavg_7d_usd
mer_012026-09-016.996.996.99
mer_012026-09-020.006.993.50
mer_012026-09-0313.9820.976.99
mer_012026-09-046.9927.966.99
mer_012026-09-05027.965.59
mer_012026-09-06027.964.66
mer_012026-09-07027.963.99
mer_012026-09-08027.963.00
mer_012026-09-096.9934.953.99
mer_012026-09-10034.952.00
mer_012026-09-1193.96128.9114.42
mer_012026-09-126.99135.9015.42
mer_012026-09-130135.9015.42
mer_012026-09-140135.9015.42
mer_012026-09-156.99142.8916.42
mer_012026-09-160142.8915.42
mer_012026-09-176.99149.8816.42
mer_012026-09-186.99156.873.99
mer_012026-09-190156.873.00
mer_012026-09-200156.873.00
348 rows (first 20 shown)
WalkthroughTry the task first: the walkthrough is most useful after your own attempt.

What it is for. Daily revenue of each merchant with a running total and a 7-day average: a typical dashboard chart.

Steps.

  1. daily: net revenue per merchant and day.
  2. A grid: merchants CROSS JOIN days, then LEFT JOIN daily with COALESCE(net_usd, 0).
  3. Windows over the grid: SUM(net_usd) OVER (PARTITION BY merchant_id ORDER BY day) for the running total, and AVG(net_usd) OVER (… ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) for the average.

Traps.

  • Without the grid, empty days drop out, and “7 rows” stop being 7 days. Only 222 merchant-days have sales; the grid has 348.
  • AVG without a frame uses the default one, from the start of the partition to the current row. That is a running average, not a 7-day one. For mer_01 on 8 September the default frame gives 3.50; the 7-day average is 3.00.
  • ROWS counts rows, so it is right only when there is exactly one row per day. The grid guarantees that.

Check. 348 rows: 12 merchants × 29 days. mer_01 has 6.99 on 1 September and a net of 0 on 2 September, so the average on the 2nd is 3.50: over the two days that exist.

In production. The windows work on a small set, days × merchants. The expensive part is reading transactions, so an index on start_time.

Q10. Churn rate per product — August 2026

Section titled “Q10. Churn rate per product — August 2026”
SQLQ10 · Difficulty: hard · Target time: 15 min

Take the paid subscriptions that were active on August 1, 2026. How many of them ended during August and were not renewed (churned)? Show it per product: active on August 1, churned, churn rate. Worst products first.

Output columns: product_id, active_at_start, churned, churn_rateOrder: ORDER BY churn_rate DESC, product_id

Ask first

Say each question out loud before you code. Open the interviewer's answer only after you asked.

  1. What is one subscription?

    All its paid periods: the first purchase and every renewal share the same original_transaction_id. Use only paid rows: not trial, not refunded, not a test purchase, not promo.

  2. Active on August 1?

    The first start_time of the subscription <= 2026-08-01 and the last end_time of the subscription > 2026-08-01.

  3. Churned in August?

    Active on August 1 and no longer active on 2026-09-01 00:00: the last end_time of the subscription <= 2026-09-01.

  4. Rate?

    churned / active_at_start, rounded to 4 decimals.

  5. Do you also need every month of the year?

    Not now. Say how you would extend it: a calendar of months instead of one date.

About the data: transactions
  • One subscription = all its rows with the same original_transaction_id: the first purchase and every renewal. Each row is one paid period, start_time to end_time.
  • So the subscription lives from the earliest start_time to the latest end_time of its paid rows. If it was active on 1 August and is no longer active on 1 September 00:00, nobody renewed it — that is churn.

A few rows

SELECT transaction_id AS id, original_transaction_id AS chain,
is_trial AS trial, is_trial_conversion AS conversion, renewal_number AS n,
start_time, end_time, revenue_usd AS net, refunded_at
FROM transactions
WHERE original_transaction_id IN ('t_000141', 't_003269')
ORDER BY chain, start_time;
idchaintrialconversionnstart_timeend_timenetrefunded_at
t_000141t_000141truefalse12025-07-06 17:45:042025-07-13 17:45:040.00NULL
t_000142t_000141falsetrue22025-07-13 17:45:042025-08-13 17:45:044.99NULL
t_000143t_000141falsefalse32025-08-13 17:45:042025-09-13 17:45:044.99NULL
t_000144t_000141falsefalse42025-09-13 17:45:042025-10-13 17:45:040.002025-09-20 20:52:05
t_003269t_003269truefalse12026-02-24 11:20:412026-03-03 11:20:410.00NULL

"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
Hint: what the interviewer would nudge

Collapse each subscription to one row first: group the paid rows by original_transaction_id and take the first start and the last end. Then active on 1 August and churned are simple conditions.

Reference solution
WITH chains AS (
SELECT original_transaction_id AS chain_id,
product_id,
MIN(start_time) AS first_start,
MAX(end_time) AS last_end
FROM transactions
WHERE NOT is_trial
AND NOT is_test
AND channel <> 'promo'
AND refunded_at IS NULL
GROUP BY original_transaction_id, product_id
),
active AS (
SELECT *
FROM chains
WHERE first_start <= TIMESTAMP '2026-08-01'
AND last_end > TIMESTAMP '2026-08-01'
)
SELECT product_id,
COUNT(*) AS active_at_start,
COUNT(*) FILTER (WHERE last_end <= TIMESTAMP '2026-09-01') AS churned,
ROUND(1.0 * COUNT(*) FILTER (WHERE last_end <= TIMESTAMP '2026-09-01') / COUNT(*), 4) AS churn_rate
FROM active
GROUP BY product_id
ORDER BY churn_rate DESC, product_id;

Expected output

product_idactive_at_startchurnedchurn_rate
prd_086070.1167
prd_105450.0926
prd_174640.0870
prd_054940.0816
prd_115340.0755
prd_075640.0714
prd_135030.0600
prd_185230.0577
prd_206230.0484
prd_014420.0455
prd_024420.0455
prd_164620.0435
prd_194620.0435
prd_125020.0400
prd_145420.0370
prd_094010.0250
prd_064410.0227
prd_035610.0179
prd_044700.0000
prd_154000.0000
20 rows
WalkthroughTry the task first: the walkthrough is most useful after your own attempt.

What it is for. Churn: of the subscriptions that were paid on 1 August, how many were not renewed in August. One subscription is all its rows with one original_transaction_id. It lives from the first start_time to the last end_time of its paid rows.

Steps.

  1. A CTE chains: paid rows only, GROUP BY original_transaction_id, product_id → MIN(start_time) and MAX(end_time).
  2. A CTE active: chains alive on 1 August.
  3. The result: GROUP BY product_id → COUNT(*), COUNT(*) FILTER (WHERE last_end <= '2026-09-01') and the rate.

Traps.

  • MAX(start_time) instead of MAX(end_time). The end of a subscription is the end of its last period.
  • last_end < '2026-09-01' misses a subscription that ends exactly at 1 September 00:00. It is active on 1 August and no longer active on 1 September, so it churned in August; with < it never counts as churn in any month. No practice chain ends exactly at that midnight. The hidden edge-case data has one, so < fails there.
  • refunded_at IS NOT NULL instead of IS NULL keeps only the refunds.
  • Forgotten trials move the start of a subscription 7 days earlier. For example, a subscription paid from 3 August after a trial from 27 July would look active on 1 August.
  • The rate needs 1.0 *; integer division gives 0.

Check. The worst product is prd_08: 7 of 60, 0.1167. In total, 993 subscriptions were active on 1 August and 52 churned.

Follow-up.

  • “And for every month of the year?” A calendar of months instead of one date: generate_series and a grid. Answer with the idea.
  • “Why is prd_08 the worst?” Look at the plans. Annual subscriptions rarely end in a given month: 14 of 696 churned in August, against 31 of 284 monthly and 7 of 13 weekly ones. So churn per plan differs much more than churn per product. prd_08 has 40 annual subscriptions out of 60; its 7 losses are 3 monthly, 3 weekly and 1 annual.

In production. The query groups the whole table, so an index does not make it cheaper: EXPLAIN shows a hash aggregate over a sequential scan, with or without an index on (original_transaction_id, start_time). Two things help. Keep a table with one row per subscription (first_start, last_end), updated with every renewal: churn for any month is then a pass over that small table. Or first pick the chains that have a period ending after 1 August (an index on end_time finds them) and group only those. On this small table one full pass is still cheaper, as EXPLAIN shows, so check it on the real one.

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