Skip to content

Calendars and active periods

“Revenue for every day of September.” “Active subscriptions on 1 June.” “MRR at the end of the month.” Two ideas sit behind these tasks. A day without data has no row, so you build the days yourself. And a subscription is a period, not an event: “active at a moment” is a condition on both of its ends, plus the refund.

GROUP BY makes groups from the rows that exist. mer_01 sold nothing from 5 to 8 September, so its daily report for 1–10 September has five rows, not ten (the query is on Shares and running totals). Those days are not zero. They are missing. A chart skips them, LAG compares 9 September with 4 September, and a 7-row moving average covers more than seven days.

generate_series(start, stop, step) returns one row per step. Both ends are included:

SELECT CAST(d AS DATE) AS day
FROM generate_series(TIMESTAMP '2026-09-01', TIMESTAMP '2026-09-05', INTERVAL '1 day') AS g(d);
day
2026-09-01
2026-09-02
2026-09-03
2026-09-04
2026-09-05

Write the ends as TIMESTAMP '…'. With plain strings the function still runs, but it returns timestamp with time zone, a different type from the columns. Unlike the half-open filter on start_time, the stop value here is the last day you want.

The full pattern: the calendar in FROM, the daily totals in a CTE, a LEFT JOIN between them, and COALESCE for the days without a match.

WITH days AS (
SELECT CAST(d AS DATE) AS day
FROM generate_series(TIMESTAMP '2026-09-01', TIMESTAMP '2026-09-10', INTERVAL '1 day') AS g(d)
),
daily AS (
SELECT 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 p.merchant_id = 'mer_01'
AND NOT t.is_test
AND t.start_time >= TIMESTAMP '2026-09-01'
AND t.start_time < TIMESTAMP '2026-09-11'
GROUP BY 1
)
SELECT d.day, COALESCE(s.net_usd, 0) AS net_usd
FROM days d
LEFT JOIN daily s ON s.day = d.day
ORDER BY d.day;
daynet_usd
2026-09-016.99
2026-09-020.00
2026-09-0313.98
2026-09-046.99
2026-09-050
2026-09-060
2026-09-070
2026-09-080
2026-09-096.99
2026-09-100

Ten rows, one per day. Look at the two kinds of zero. On 2 September there is a real row: a free trial with a price of 0.00. On 5 September there is no row at all, and COALESCE puts 0 there.

Three rules keep the zeros alive:

  • The calendar is on the left. It decides which rows exist; the data only fills them.
  • Filters on the data stay in its CTE (or in ON). A condition on s in the WHERE after the join removes the empty days again. See LEFT JOIN and zeros.
  • Aggregate before the join. Join the calendar to daily totals, not to raw transactions. Otherwise you count rows of the join, and an empty day becomes 1.

The same works for months: generate_series(TIMESTAMP '2026-01-01', TIMESTAMP '2026-09-01', INTERVAL '1 month') and date_trunc('month', start_time) on the data side. When the task does not say, ask: “Should days with no sales be in the result, with zero?”

One row of transactions is one billing period [start_time, end_time): the start belongs to it, the end does not. A refund ends the subscription at refunded_at. So a paid subscription is active at moment m when:

SELECT COUNT(*) AS active
FROM transactions
WHERE NOT is_trial AND NOT is_test AND channel <> 'promo'
AND start_time <= TIMESTAMP '2026-06-01'
AND end_time > TIMESTAMP '2026-06-01'
AND (refunded_at IS NULL OR refunded_at > TIMESTAMP '2026-06-01');
active
940
  • start_time <= m: it has started. A period that starts exactly at m is active at m.
  • end_time > m: it has not ended. A period that ends exactly at m is already over.
  • refunded_at IS NULL OR refunded_at > m: there was no refund, or it came later.

AND binds tighter than OR. Without the brackets, the last line reads as “(all the filters AND refunded_at IS NULL) OR refunded_at > m”. The second half lets in any row with a later refund: test purchases, trials, periods that ended long ago. The same query without the brackets returns 988. Without the refund check at all it returns 960. The rule: when a WHERE contains OR, put brackets around it. Filters and dates has a trap about exactly this.

“Active at any time in September” is a different question. Two half-open periods [a, b) and [c, d) overlap when a < d AND c < b. For September that is start_time < TIMESTAMP '2026-10-01' AND end_time > TIMESTAMP '2026-09-01', plus the refund check at the start of the month.

SELECT COUNT(*) AS periods,
COUNT(DISTINCT original_transaction_id) AS subscriptions
FROM transactions
WHERE NOT is_trial AND NOT is_test AND channel <> 'promo'
AND start_time < TIMESTAMP '2026-10-01'
AND end_time > TIMESTAMP '2026-09-01'
AND (refunded_at IS NULL OR refunded_at > TIMESTAMP '2026-09-01');
periodssubscriptions
14961126

A monthly subscription that renews on 10 September has two periods in September: the one that ends that day and the one that starts. So count subscriptions with COUNT(DISTINCT original_transaction_id), the id that all renewals of one chain share. At a single moment the two counts are equal (940 and 940), because the periods of one chain never overlap.

For “active subscriptions on every day”, combine both ideas: the calendar on the left, the subscriptions joined ON the active condition with the day as m, and a count per day.

TalkSay it out loud

How would you count active subscriptions for every day of September?

Say your answer out loud first, then open it.

Show the answer

“I build a calendar with generate_series and join the subscriptions to it on the active condition, with the day as the moment. Then I count per day. The calendar is on the left, so a day with no active subscriptions stays in the result with zero.”

MRR (monthly recurring revenue) is a value at a moment, not a sum over a period. Take the subscriptions active at m and bring each price to one month: a weekly price × 52 / 12, a monthly price × 1, a yearly price × 1 / 12. Watch the integer division:

SELECT 52 / 12 AS int_div, 52.0 / 12 AS weekly_factor, 1 / 12 AS int_year, 1.0 / 12 AS yearly_factor;
int_divweekly_factorint_yearyearly_factor
44.333333333333333300.08333333333333333333

52 / 12 is 4 and 1 / 12 is 0: every yearly subscription would add nothing. Write 52.0 / 12 and 1.0 / 12. MRR on 1 June by plan period:

SELECT plan_period,
COUNT(*) AS active,
ROUND(SUM(charged_usd * CASE plan_period
WHEN 'P1W' THEN 52.0 / 12
WHEN 'P1M' THEN 1
WHEN 'P1Y' THEN 1.0 / 12
END), 2) AS mrr_usd
FROM transactions
WHERE NOT is_trial AND NOT is_test AND channel <> 'promo'
AND start_time <= TIMESTAMP '2026-06-01'
AND end_time > TIMESTAMP '2026-06-01'
AND (refunded_at IS NULL OR refunded_at > TIMESTAMP '2026-06-01')
GROUP BY plan_period
ORDER BY plan_period;
plan_periodactivemrr_usd
P1M2772244.23
P1W14181.39
P1Y6492871.96

The 940 active subscriptions give 5297.58 per month. Two choices in this query are worth saying out loud:

  • charged_usd, not revenue_usd. revenue_usd is already 0 for a subscription that was refunded later, after m. On 1 June it gives 5269.61, because three subscriptions refunded later count as 0.
  • CASE without ELSE returns NULL for a period it does not know, and SUM skips NULL without a word. Check the values first: SELECT DISTINCT plan_period FROM transactions.
SQLWrite a query

New paid South Market subscriptions per day for 1–10 September 2026, including days with zero: channel = 'south_market', renewal_number = 1, not a trial, not a test purchase. Day as DATE.

Output columns: day, new_subscriptionsOrder: ORDER BY day

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)
  • renewal_number — 1 = first purchase of the chain, then 2, 3 … for renewals
  • start_time — start of the period = time of purchase; "started in …" means this column
  • is_test — test purchase: exclude it from business numbers
channelis_trialrenewal_numberstart_timeis_test
north_marketfalse12025-01-01 04:48:03false
north_marketfalse12025-01-01 06:59:58false
north_marketfalse12025-01-01 02:08:33false

"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

WITH days AS (
SELECT CAST(d AS DATE) AS day
FROM generate_series(TIMESTAMP '2026-09-01', TIMESTAMP '2026-09-10', INTERVAL '1 day') AS g(d)
),
new_subs AS (
SELECT CAST(start_time AS DATE) AS day, COUNT(*) AS n
FROM transactions
WHERE channel = 'south_market' AND renewal_number = 1 AND NOT is_trial AND NOT is_test
AND start_time >= TIMESTAMP '2026-09-01'
AND start_time < TIMESTAMP '2026-09-11'
GROUP BY 1
)
SELECT d.day, COALESCE(n.n, 0) AS new_subscriptions
FROM days d
LEFT JOIN new_subs n ON n.day = d.day
ORDER BY d.day;

Expected output

daynew_subscriptions
2026-09-010
2026-09-020
2026-09-033
2026-09-042
2026-09-052
2026-09-061
2026-09-070
2026-09-080
2026-09-092
2026-09-102
10 rows

Every day, even empty: a calendar from generate_series, a LEFT JOIN to the daily counts, and COALESCE(…, 0). On South Market four of these ten days have no new subscription (1, 2, 7 and 8 September). A query without the calendar returns 6 rows instead of 10 and fails Check.

SQLWrite a querycore

Active paid subscriptions per channel at 2026-09-10 00:00. A refund ends a subscription at refunded_at.

Output columns: channel, activeOrder: 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
  • end_time — end of the period, not included: the period is [start_time, end_time)
  • 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_timeend_timerefunded_atis_test
north_marketfalse2025-01-01 04:48:032026-01-01 04:48:03NULLfalse
north_marketfalse2025-01-01 02:08:332025-02-01 02:08:33NULLfalse
north_marketfalse2025-01-22 14:37:002026-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 active
FROM transactions
WHERE NOT is_trial AND NOT is_test AND channel <> 'promo'
AND start_time <= TIMESTAMP '2026-09-10'
AND end_time > TIMESTAMP '2026-09-10'
AND (refunded_at IS NULL OR refunded_at > TIMESTAMP '2026-09-10')
GROUP BY channel
ORDER BY channel;

Expected output

channelactive
north_market616
south_market374
web81
3 rows

Active at m: start_time <= m AND end_time > m, and the refund either did not happen or happened after m. The brackets around OR are required: without them the refund condition escapes all the other filters. The hidden data has a period that ends exactly at 2026-09-10 00:00: with end_time >= m it would count as active.

SQLWrite a querycore

MRR per channel at 2026-09-30 00:00: active paid subscriptions (not refunded at that moment); monthly value = charged_usd × (P1W: 52/12, P1M: 1, P1Y: 1/12). Rounded to 2 decimals.

Output columns: channel, mrr_usdOrder: ORDER BY channel

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)
  • start_time — start of the period = time of purchase; "started in …" means this column
  • end_time — end of the period, not included: the period is [start_time, end_time)
  • charged_usd — what the customer paid (gross)
  • 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
plan_periodchannelis_trialstart_timeend_timecharged_usdrefunded_atis_test
P1Mnorth_marketfalse2025-01-01 02:08:332025-02-01 02:08:336.99NULLfalse
P1Mnorth_marketfalse2025-01-01 06:59:582025-02-01 06:59:586.99NULLfalse
P1Mnorth_marketfalse2025-01-23 06:44:232025-02-23 06:44:237.992025-02-09 20:47:28false

"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(charged_usd * CASE plan_period
WHEN 'P1W' THEN 52.0 / 12
WHEN 'P1M' THEN 1
WHEN 'P1Y' THEN 1.0 / 12
END), 2) AS mrr_usd
FROM transactions
WHERE NOT is_trial AND NOT is_test AND channel <> 'promo'
AND start_time <= TIMESTAMP '2026-09-30'
AND end_time > TIMESTAMP '2026-09-30'
AND (refunded_at IS NULL OR refunded_at > TIMESTAMP '2026-09-30')
GROUP BY channel
ORDER BY channel;

Expected output

channelmrr_usd
north_market3271.75
south_market2042.97
web482.24
3 rows

MRR is a value at a moment: the active subscriptions, each brought to a month with CASE inside SUM. Write 52.0 / 12, not 52 / 12: integer division would give 4. The active condition is the same as in the previous drill, with its brackets. The hidden data has a period that ends exactly at 2026-09-30 00:00, so end_time >= m fails here too.

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