Skip to content

Subscriptions over time

A subscription is a period, not a single moment. Q03 and Q04 count the periods active at a moment, Q06 measures the break between two periods, and Q07 reads the latest row of each customer. The traps sit at the boundaries: the end of a period, a refund, an empty day, two rows with the same time. The background is on Calendars and active periods, Top N per group and Shares and running totals, where LAG is explained.

SQLQ03 · Difficulty: easy · Target time: 8 min

How many paid subscriptions were active on 2026-09-01 00:00 UTC, per product?

Output columns: product_id, active_subscriptionsOrder: ORDER BY active_subscriptions DESC, product_id

Ask first

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

  1. What does "active" mean for one transaction?

    start_time <= moment < end_time (half-open interval).

  2. Paid means?

    Not a trial, not a test purchase, channel is not 'promo'.

  3. What about refunds?

    A refunded transaction stops being active at refunded_at. If refunded_at <= moment, it is not active.

  4. Products with zero?

    Leave them out.

About the data: transactions
  • One row in transactions is one subscription period: a purchase, a renewal or a trial. Renewals of the same subscription are separate rows.
  • A period is active at moment m if start_time <= m < end_time.
  • A refund ends the period: from refunded_at on, it is not active.
  • A paid row is not a trial, not a test purchase, and channel <> 'promo' (promo means free access).
  • In the example, period t_000144 runs until October 13, 2025, but it was refunded on September 20 — from September 20 it is no longer active.

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

Write the condition for one row first: when is a period active at exactly 1 September 00:00? Then add what makes it paid and what a refund changes.

Reference solution
SELECT product_id,
COUNT(*) AS active_subscriptions
FROM transactions
WHERE start_time <= TIMESTAMP '2026-09-01'
AND end_time > TIMESTAMP '2026-09-01'
AND NOT is_trial
AND NOT is_test
AND channel <> 'promo'
AND (refunded_at IS NULL OR refunded_at > TIMESTAMP '2026-09-01')
GROUP BY product_id
ORDER BY active_subscriptions DESC, product_id;

Expected output

product_idactive_subscriptions
prd_0869
prd_2064
prd_0462
prd_0357
prd_1157
prd_1457
prd_1857
prd_0755
prd_1254
prd_1654
prd_1053
prd_0551
prd_1551
prd_0650
prd_0148
prd_1348
prd_1947
prd_1746
prd_0244
prd_0944
20 rows
WalkthroughTry the task first: the walkthrough is most useful after your own attempt.

What it is for. How many paying subscribers each product had on 1 September. This number is the base of MRR and churn. A period is active at moment m if m is inside [start_time, end_time).

Steps. One WHERE and one GROUP BY product_id:

  • active: start_time <= m AND end_time > m;
  • paid: not a trial, not a test purchase, not promo access;
  • a refund before the moment cancels the period: refunded_at IS NULL OR refunded_at > m.

Traps.

  • end_time >= m counts a period that ended exactly at that midnight, and refunded_at >= m keeps one refunded exactly then. No practice row sits on this boundary. The hidden edge-case data that Check also uses has both cases, so either mistake fails there.
  • A plain refunded_at IS NULL drops periods refunded after 1 September. At that moment they were still active. Here it loses 4 subscriptions: 1064 instead of 1068.

Check. The first row is prd_08 with 69. The sum over all products is 1068, the same as the first day of Q04.

Follow-up. “And for every day of September?” That is Q04: a calendar and the same count for each day.

In production. start_time <= m AND end_time > m is two ranges. A B-tree on start_time cuts off the future periods, but every past period must still be read. For “active at a moment”, a range column tsrange(start_time, end_time) with a GiST index and the @> operator answers the question directly.

Q04. Daily active subscriptions — September 2026

Section titled “Q04. Daily active subscriptions — September 2026”
SQLQ04 · Difficulty: medium · Target time: 15 min

For every day of September 2026, show how many paid subscriptions were active at 00:00 UTC of that day. Every day must appear, even with 0.

Output columns: day (DATE), active_subscriptionsOrder: ORDER BY day

Ask first

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

  1. Same definition of active and paid as in Q03?

    Yes.

  2. Days?

    2026-09-01 … 2026-09-30, 30 rows. Hint: generate_series.

  3. Why not GROUP BY start_time?

    A subscription is active on many days, not only on the day it started.

  4. Can I simply repeat the Q03 count for every day?

    Yes, any correct way is fine.

About the data: transactions
  • Active at moment m works as in q03: start_time <= m < end_time, and a refund ends the period.
  • A paid row is not a trial, not a test purchase, and channel <> 'promo' (promo means free access).
  • Every day, even a day with no data, comes from a calendar: generate_series(start, end, INTERVAL '1 day').

"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

You already have the count for one moment from Q03. Generate the 30 days first, attach that count to each day, and think about a day with no rows at all.

Reference solution
WITH days AS (
SELECT d AS day_start
FROM generate_series(TIMESTAMP '2026-09-01', TIMESTAMP '2026-09-30', INTERVAL '1 day') AS g(d)
)
SELECT CAST(days.day_start AS DATE) AS day,
COUNT(t.transaction_id) AS active_subscriptions
FROM days
LEFT JOIN transactions t
ON t.start_time <= days.day_start
AND t.end_time > days.day_start
AND NOT t.is_trial
AND NOT t.is_test
AND t.channel <> 'promo'
AND (t.refunded_at IS NULL OR t.refunded_at > days.day_start)
GROUP BY days.day_start
ORDER BY day;

Expected output

dayactive_subscriptions
2026-09-011068
2026-09-021063
2026-09-031063
2026-09-041064
2026-09-051066
2026-09-061066
2026-09-071068
2026-09-081068
2026-09-091067
2026-09-101071
2026-09-111072
2026-09-121076
2026-09-131079
2026-09-141079
2026-09-151075
2026-09-161074
2026-09-171068
2026-09-181063
2026-09-191064
2026-09-201067
30 rows (first 20 shown)
WalkthroughTry the task first: the walkthrough is most useful after your own attempt.

What it is for. The same metric as Q03, but for each day. This is the line on an “active subscriptions” chart.

Steps. A calendar of days from generate_series, and for each day the count from Q03. There are two ways:

  • simpler: a subquery in SELECT, (SELECT COUNT(*) FROM transactions t WHERE … d …), once per day;
  • classic, as in the reference: the calendar LEFT JOIN transactions on the condition “active on this day”, then COUNT(t.transaction_id).

Traps.

  • With LEFT JOIN, every condition on transactions goes into ON, not into WHERE. Otherwise the empty days disappear.
  • COUNT(t.transaction_id), not COUNT(*): an empty day has one row with NULLs, and COUNT(*) shows 1 for it.

Check. 30 rows. 1 September — 1068, 2 September — 1063, 30 September — 1044. Every practice day has more than 1000 active subscriptions, so neither trap changes the result here. The hidden edge-case data has a day when nothing is active: there a WHERE loses the day, COUNT(*) shows 1, and Check fails.

Follow-up. “And on a billion rows?” Do not recompute history for every day on every run.

In production. Keep a daily snapshot table: one row per day and product, written by a job once a day. The report then reads 30 rows instead of scanning transactions 30 times. The same count in Python, in O(n + days), is task P05 on Events and time.

Q06. Customers who came back after a break

Section titled “Q06. Customers who came back after a break”
SQLQ06 · Difficulty: medium · Target time: 12 min

Find customers who came back to the same product after a break of more than 30 days: the next transaction started more than 30 days after the previous one ended.

Output columns: customer_id, product_id, lapsed_on (DATE), returned_on (DATE), gap_daysOrder: ORDER BY returned_on, customer_id, product_id

Ask first

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

  1. Per product or across products?

    Per (customer_id, product_id).

  2. "Previous" by what order?

    By start_time, then transaction_id.

  3. How is the gap measured?

    Condition: start_time > previous end_time + 30 days. gap_days = returned_on - lapsed_on, both as DATE.

  4. Test?

    Excluded.

  5. Trials, promo access, refunds?

    Keep all those rows. For a refunded period, still use its end_time.

About the data: transactions
  • A customer's history in a product is their rows with the same (customer_id, product_id), in start_time order.
  • A break is the gap from one row's end_time to the next row's start_time.
  • In the example, chain t_000141 has no breaks: each start_time equals the previous end_time.

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

You need to compare each row with the previous row of the same customer and product. Which window function gives you the previous end_time?

Reference solution
WITH ordered AS (
SELECT customer_id,
product_id,
start_time,
LAG(end_time) OVER (PARTITION BY customer_id, product_id
ORDER BY start_time, transaction_id) AS prev_end
FROM transactions
WHERE NOT is_test
)
SELECT customer_id,
product_id,
CAST(prev_end AS DATE) AS lapsed_on,
CAST(start_time AS DATE) AS returned_on,
CAST(start_time AS DATE) - CAST(prev_end AS DATE) AS gap_days
FROM ordered
WHERE start_time > prev_end + INTERVAL '30 days'
ORDER BY returned_on, customer_id, product_id;

Expected output

customer_idproduct_idlapsed_onreturned_ongap_days
cus_00338prd_032025-02-092025-05-0787
cus_01112prd_172025-02-282025-05-0869
cus_02066prd_042025-01-282025-05-09101
cus_01730prd_102025-03-102025-05-1667
cus_02162prd_172025-03-102025-05-3182
cus_02028prd_112025-04-162025-06-2974
cus_01987prd_052025-05-162025-07-1358
cus_02254prd_052025-05-192025-07-2365
cus_00445prd_042025-04-112025-07-26106
cus_02365prd_202025-06-092025-08-0759
cus_00841prd_032025-07-112025-08-1030
cus_01027prd_102025-04-262025-08-11107
cus_01666prd_142025-06-032025-08-1169
cus_00908prd_062025-07-042025-08-1744
cus_00693prd_072025-05-172025-08-2196
cus_02357prd_192025-06-052025-08-2783
cus_02104prd_052025-06-132025-09-0382
cus_01045prd_162025-07-272025-09-0944
cus_01044prd_152025-08-032025-09-1644
cus_01232prd_122025-06-122025-09-1898
121 rows (first 20 shown)
WalkthroughTry the task first: the walkthrough is most useful after your own attempt.

What it is for. Win-back: customers who left for more than 30 days and then returned. Marketing uses it to see which products bring people back.

Steps.

  1. A CTE with LAG(end_time) OVER (PARTITION BY customer_id, product_id ORDER BY start_time, transaction_id): the end of the previous period of the same customer in the same product.
  2. In the next step, WHERE start_time > prev_end + INTERVAL '30 days'.

Traps.

  • A window function cannot be used in the WHERE of the same SELECT. The filter goes into the next step.
  • The gap in days is the difference of two DATE values, CAST(start_time AS DATE) - CAST(prev_end AS DATE), which is an integer. The difference of two timestamps is an interval.
  • transaction_id in the window’s ORDER BY decides which row is “previous” when two rows start at the same time. The hidden edge-case data has such customers: a weekly and a monthly plan bought at the same moment, then a return after a break. With the weekly plan first (it has the smaller id), the break runs from the end of the monthly plan: 45 days. In the other order it would run from the end of the weekly plan: 68 days, while the customer still had the monthly plan. Without the tie-breaker the database picks the order by chance, and Check fails there.
  • The first row of each customer has no previous row, so prev_end is NULL. The comparison gives NULL, and the row drops out by itself. Mention it, so it does not look like luck.

Check. 121 rows. The first one: cus_00338 in prd_03 lapsed on 2025-02-09 and came back on 2025-05-07, 87 days later.

In production. The window sorts the rows of each (customer_id, product_id) by time. For one customer, an index on (customer_id, product_id, start_time) finds those rows already in that order. For a pass over the whole table it does not help: EXPLAIN here shows a sequential scan and a sort even with that index, because the query reads every row anyway. A covering index with every column the query reads, (customer_id, product_id, start_time, transaction_id) INCLUDE (end_time, is_test), does give an index-only scan with no sort, after VACUUM. Check EXPLAIN before you promise that an index removes a sort.

SQLQ07 · Difficulty: medium · Target time: 10 min

For each (customer, product) take the latest transaction and give the customer a status: 'trial', 'active' or 'expired'. Count customers per product and status.

Output columns: product_id, status, customersOrder: ORDER BY product_id, status

Ask first

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

  1. Latest by what?

    start_time DESC, then transaction_id DESC.

  2. Status rules at today = 2026-09-30 00:00?

    Only end_time and refunded_at decide, start_time does not. end_time > today and refunded_at IS NULL: 'trial' if it is a trial, otherwise 'active'. Everything else is 'expired'.

  3. Which transactions do we look at?

    Test and promo excluded.

About the data: transactions
  • A customer's latest row in a product is the one with the latest start_time among rows with the same (customer_id, product_id).
  • The status comes from that row: end_time compared with 'today' (2026-09-30), is_trial, refunded_at.

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

First find each customer's latest row per product, for example with ROW_NUMBER. The status is then a CASE on that one row.

Reference solution
WITH latest AS (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY customer_id, product_id
ORDER BY start_time DESC, transaction_id DESC) AS rn
FROM transactions
WHERE NOT is_test
AND channel <> 'promo'
)
SELECT product_id,
CASE
WHEN end_time > TIMESTAMP '2026-09-30' AND refunded_at IS NULL AND is_trial THEN 'trial'
WHEN end_time > TIMESTAMP '2026-09-30' AND refunded_at IS NULL THEN 'active'
ELSE 'expired'
END AS status,
COUNT(*) AS customers
FROM latest
WHERE rn = 1
GROUP BY 1, 2
ORDER BY product_id, status;

Expected output

product_idstatuscustomers
prd_01active45
prd_01expired56
prd_02active41
prd_02expired60
prd_03active58
prd_03expired58
prd_04active56
prd_04expired118
prd_05active52
prd_05expired47
prd_06active44
prd_06expired57
prd_07active56
prd_07expired65
prd_08active65
prd_08expired124
prd_08trial1
prd_09active42
prd_09expired65
prd_10active52
41 rows (first 20 shown)
WalkthroughTry the task first: the walkthrough is most useful after your own attempt.

What it is for. A snapshot of who pays now, who is on a trial and who has left, per product. It is the base of a subscriber dashboard.

Steps.

  1. ROW_NUMBER() OVER (PARTITION BY customer_id, product_id ORDER BY start_time DESC, transaction_id DESC); rn = 1 is the customer’s latest row.
  2. A CASE on that row, with end_time and refunded_at only: end_time after today and no refund → ‘trial’ or ‘active’; everything else → ‘expired’.
  3. GROUP BY product_id, status.

Traps.

  • The status comes from the latest row, not from any row of the customer.
  • The order of the CASE branches matters: ‘trial’ before ‘active’. In the other order, the only trial in the practice data (in prd_08) becomes ‘active’, and the result has 40 rows instead of 41.
  • Without transaction_id DESC, two rows with the same start_time give a random “latest” row. The hidden edge-case data has such pairs, a trial and a paid month bought at the same moment, so the random pick changes the counts there.

Without a window. MAX(start_time) per (customer, product) in a CTE, then a JOIN back to transactions. It works until two rows share the latest time: then the join returns both, and the customer is counted twice. The practice data has no such pair. Check’s hidden edge-case data has them, so this version fails there.

Check. 41 rows: 20 products × (‘active’, ‘expired’), plus one ‘trial’. In total there are 2490 customer–product pairs: 1044 active, 1445 expired and 1 trial.

Follow-up. “What about 50 million customers?” Keep a table of current statuses, one row per customer and product, updated from webhooks with INSERT … ON CONFLICT DO UPDATE.

In production. The real answer is the table of current statuses from the follow-up: the service should not compute a status from history every time. An index on (customer_id, product_id, start_time DESC) finds one customer’s latest row quickly. For the whole table it does not remove the sort: the query reads every row and every column, and EXPLAIN here shows a sequential scan and a sort even with that index.

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