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.
Step 1: the cohort
Section titled “Step 1: the cohort”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 cohortFROM 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.
Step 2: retained, with EXISTS
Section titled “Step 2: retained, with EXISTS”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 retainedFROM cohort c;| cohort | retained |
|---|---|
| 111 | 47 |
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 becauseDISTINCThides 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).
Step 3: the share
Section titled “Step 3: the share”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.
What “retained” means: ask
Section titled “What “retained” means: ask”“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 retainedFROM first_paid fWHERE f.first_at >= TIMESTAMP '2026-06-01' AND f.first_at < TIMESTAMP '2026-07-01'GROUP BY f.plan_periodORDER BY f.plan_period;| plan_period | cohort | retained |
|---|---|---|
| P1M | 50 | 40 |
| P1W | 12 | 7 |
| P1Y | 49 | 0 |
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.
The cohort table: months by months
Section titled “The cohort table: months by months”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_shareFROM gridWHERE cohort_month >= DATE '2026-01-01' AND cohort_month < DATE '2026-07-01'GROUP BY cohort_monthORDER BY cohort_month;| cohort_month | m0 | m1 | m2 | m3 | m3_share |
|---|---|---|---|---|---|
| 2026-01-01 | 102 | 40 | 28 | 24 | 0.235 |
| 2026-02-01 | 72 | 42 | 29 | 24 | 0.333 |
| 2026-03-01 | 103 | 46 | 27 | 24 | 0.233 |
| 2026-04-01 | 108 | 44 | 33 | 22 | 0.204 |
| 2026-05-01 | 106 | 55 | 41 | 38 | 0.358 |
| 2026-06-01 | 111 | 47 | 36 | 26 | 0.234 |
How it is built:
paidhas one row per customer and month, thanks toDISTINCT. That is why theJOINingridis safe here: it cannot multiply a customer within a month.m0is the cohort size, and the June row repeats the numbers above: 111 and 47. Divide any cell bym0to get its share.month_numbercounts whole months between the two month starts.EXTRACTreturnsnumeric, so the result is cast toINT.- Future cells. For a recent cohort, the later columns are months that have not happened yet, and
COUNTreturns 0 for them, which reads like “everyone left”. This table stops at the June cohort, so itsm3is 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.
Practice
Section titled “Practice”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 customerchannel— 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 columnis_test— test purchase: exclude it from business numbers
| customer_id | channel | is_trial | start_time | is_test |
|---|---|---|---|---|
| cus_00001 | south_market | false | 2025-10-12 16:30:29 | false |
| cus_00002 | south_market | false | 2025-06-25 19:26:50 | false |
| cus_00003 | south_market | false | 2025-02-27 08:20:21 | false |
"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 rateFROM flagged;Expected output
| cohort | retained | rate |
|---|---|---|
| 99 | 47 | 0.475 |
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.
Further reading
Section titled “Further reading”- 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.
Related topics
Section titled “Related topics”- Subqueries and CTE —
EXISTS,NOT EXISTSand step-by-step CTEs. - Filters and dates — months as half-open ranges and
date_trunc. - Row multiplication — why the
JOINcounts payments, not customers. - Conditional aggregation —
COUNT(*) FILTERand the integer division trap. - Calendars and active periods — “active at a moment”, for retention by subscription.
- Conversion and churn — trial conversion and churn, the other side of retention.
Site content: CC BY 4.0. Code: MIT. The exercises run in your browser: PostgreSQL by PGlite, Python by Pyodide.