Skip to content

Cohorts and retention

“Of the customers who first paid in June, how many paid again in July?” is a cohort question. It takes three steps: find each customer’s first paid month over all time, check whether each one paid in the next month, then divide. Two mistakes break it without an error: a first purchase computed inside the report window, and a JOIN that counts payments instead of customers.

A paid transaction is not a trial, not a test purchase and not promo access. The cohort is defined by each customer’s first one:

WITH paid AS (
SELECT customer_id, start_time
FROM transactions
WHERE NOT is_trial AND NOT is_test AND channel <> 'promo'
),
first_paid AS (
SELECT customer_id, MIN(start_time) AS first_at -- over all time
FROM paid
GROUP BY customer_id
),
cohort AS (
SELECT customer_id
FROM first_paid
WHERE first_at >= TIMESTAMP '2026-06-01' AND first_at < TIMESTAMP '2026-07-01'
)
SELECT COUNT(*) AS cohort
FROM cohort;

The June cohort has 111 customers.

The usual mistake is to filter the payments to June before the MIN. Then every customer who paid in June gets June as their “first” month, including those who first paid a year ago. That cohort has 393 customers, and most of them are not new.

Ask how far back the data goes. The practice data starts on 1 January 2025. A customer who first paid before that would look new in the first months, so early cohorts are less reliable than the 2026 ones.

For each customer of the cohort, the question is yes or no: is there at least one paid transaction in July? That is exactly what EXISTS answers. The query continues from the same three CTEs:

SELECT COUNT(*) AS cohort,
COUNT(*) FILTER (WHERE EXISTS (
SELECT 1
FROM paid p
WHERE p.customer_id = c.customer_id -- the link to the outer customer
AND p.start_time >= TIMESTAMP '2026-07-01'
AND p.start_time < TIMESTAMP '2026-08-01'
)) AS retained
FROM cohort c;
cohortretained
11147

EXISTS gives true or false for each outer row and never multiplies rows. SELECT 1 is a convention: what the subquery selects does not matter, only whether it finds a row. More on EXISTS is in Subqueries and CTE.

Two mistakes give a wrong number here:

  • A JOIN instead of EXISTS. Joining the cohort to the July payments returns 53 rows, because some customers paid twice in July. COUNT(*) then says 53. COUNT(DISTINCT c.customer_id) gives 47 again, but only because DISTINCT hides the extra rows. Row multiplication explains why.
  • No link to the outer row. Without p.customer_id = c.customer_id, the subquery asks “did anyone pay in July?”. The answer is yes for everyone, and retained becomes 111, or 100 %. A share of exactly 100 % or 0 % is a reason to check the query before you say “done” (the plausibility check of the interview protocol).

In PostgreSQL, an integer divided by an integer is an integer: 47 / 111 is 0. Multiply by 1.0 first: ROUND(1.0 * 47 / 111, 3) is 0.423. The same trap appears on Conditional aggregation.

To use the EXISTS once and not twice (for retained and for the share), compute it as a column in one more CTE: one row per customer with a boolean retained. The final SELECT then counts COUNT(*) FILTER (WHERE retained) and divides.

“Paid again next month” fits monthly plans. A yearly subscriber does not pay next month, but has not left. Split the June cohort by the plan of the first payment:

WITH paid AS (
SELECT customer_id, start_time, plan_period
FROM transactions
WHERE NOT is_trial AND NOT is_test AND channel <> 'promo'
),
first_paid AS ( -- the first payment and its plan
SELECT DISTINCT ON (customer_id) customer_id, start_time AS first_at, plan_period
FROM paid
ORDER BY customer_id, start_time
)
SELECT f.plan_period,
COUNT(*) AS cohort,
COUNT(*) FILTER (WHERE EXISTS (
SELECT 1
FROM paid p
WHERE p.customer_id = f.customer_id
AND p.start_time >= TIMESTAMP '2026-07-01'
AND p.start_time < TIMESTAMP '2026-08-01'
)) AS retained
FROM first_paid f
WHERE f.first_at >= TIMESTAMP '2026-06-01'
AND f.first_at < TIMESTAMP '2026-07-01'
GROUP BY f.plan_period
ORDER BY f.plan_period;
plan_periodcohortretained
P1M5040
P1W127
P1Y490

Forty of the 50 monthly customers paid again, and none of the 49 yearly ones, as expected. So ask before you write the query: “Does retained mean a new payment, or an active subscription?” For an active subscription, the check becomes “active at a moment”, as on Calendars and active periods.

A follow-up often asks for every cohort and several months at once. Each row is a cohort month, and each column is the number of months since the first payment:

WITH paid AS ( -- one row per (customer, month)
SELECT DISTINCT customer_id,
CAST(date_trunc('month', start_time) AS DATE) AS month
FROM transactions
WHERE NOT is_trial AND NOT is_test AND channel <> 'promo'
),
first_paid AS (
SELECT customer_id, MIN(month) AS cohort_month
FROM paid
GROUP BY customer_id
),
grid AS (
SELECT f.cohort_month,
CAST(12 * (EXTRACT(YEAR FROM p.month) - EXTRACT(YEAR FROM f.cohort_month))
+ EXTRACT(MONTH FROM p.month) - EXTRACT(MONTH FROM f.cohort_month) AS INT) AS month_number,
p.customer_id
FROM first_paid f
JOIN paid p ON p.customer_id = f.customer_id
)
SELECT cohort_month,
COUNT(*) FILTER (WHERE month_number = 0) AS m0,
COUNT(*) FILTER (WHERE month_number = 1) AS m1,
COUNT(*) FILTER (WHERE month_number = 2) AS m2,
COUNT(*) FILTER (WHERE month_number = 3) AS m3,
ROUND(1.0 * COUNT(*) FILTER (WHERE month_number = 3)
/ COUNT(*) FILTER (WHERE month_number = 0), 3) AS m3_share
FROM grid
WHERE cohort_month >= DATE '2026-01-01' AND cohort_month < DATE '2026-07-01'
GROUP BY cohort_month
ORDER BY cohort_month;
cohort_monthm0m1m2m3m3_share
2026-01-011024028240.235
2026-02-01724229240.333
2026-03-011034627240.233
2026-04-011084433220.204
2026-05-011065541380.358
2026-06-011114736260.234

How it is built:

  • paid has one row per customer and month, thanks to DISTINCT. That is why the JOIN in grid is safe here: it cannot multiply a customer within a month.
  • m0 is the cohort size, and the June row repeats the numbers above: 111 and 47. Divide any cell by m0 to get its share.
  • month_number counts whole months between the two month starts. EXTRACT returns numeric, so the result is cast to INT.
  • Future cells. For a recent cohort, the later columns are months that have not happened yet, and COUNT returns 0 for them, which reads like “everyone left”. This table stops at the June cohort, so its m3 is September, the last month of the data. For later cohorts, show such cells as NULL instead of 0.

In an interview, the long form (cohort_month, month_number, customers) is often enough; the pivot is for reading.

SQLWrite a querycore

Customers whose first paid transaction (any product) started in July 2026: how many of them also had a paid transaction that started in August 2026? Return cohort, retained, rate (3 decimals).

Output columns: cohort, retained, rate

Tables, columns and how they connect

transactions — one row = one paid (or trial) period of a subscription

  • customer_id — the customer
  • 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
  • is_test — test purchase: exclude it from business numbers
customer_idchannelis_trialstart_timeis_test
cus_00001south_marketfalse2025-10-12 16:30:29false
cus_00002south_marketfalse2025-06-25 19:26:50false
cus_00003south_marketfalse2025-02-27 08:20:21false

"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 paid AS (
SELECT customer_id, start_time
FROM transactions
WHERE NOT is_trial AND NOT is_test AND channel <> 'promo'
),
first_paid AS (
SELECT customer_id, MIN(start_time) AS first_at
FROM paid
GROUP BY customer_id
),
cohort AS (
SELECT customer_id
FROM first_paid
WHERE first_at >= TIMESTAMP '2026-07-01' AND first_at < TIMESTAMP '2026-08-01'
),
flagged AS (
SELECT c.customer_id,
EXISTS (
SELECT 1 FROM paid p
WHERE p.customer_id = c.customer_id
AND p.start_time >= TIMESTAMP '2026-08-01' AND p.start_time < TIMESTAMP '2026-09-01'
) AS retained
FROM cohort c
)
SELECT COUNT(*) AS cohort,
COUNT(*) FILTER (WHERE retained) AS retained,
ROUND(1.0 * COUNT(*) FILTER (WHERE retained) / COUNT(*), 3) AS rate
FROM flagged;

Expected output

cohortretainedrate
99470.475
1 row

The cohort comes from the first payment, a MIN per customer over all time, and then a check “was there a payment in the next month”. The order of steps is paid → first_paid → cohort → flagged → the count. EXISTS with a link to the outer customer counts each customer once. It is written once, in flagged, as a retained flag per customer, and the final query counts that flag for both retained and the rate. The share needs 1.0 * before the division.

  • EXISTS — a subquery that only answers “is there at least one row”.
  • Aggregate expressions — FILTER (WHERE …) on an aggregate.
  • date_trunc — the start of the month as the cohort key.
  • WITH queries — the CTE steps the cohort is built from.

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