Multi-Step Cohort & Retention Analysis Using CTEs
Build cohort tables and retention curves with staged CTE transforms.
In plain words
Group people by the month they joined, then check how many from each group came back in later months.
Think of it like…
Tracking a school's intake classes: of the students who joined in 2023, how many are still enrolled in their second year, their third year? You compare each intake with itself over time, not with other years' totals.
Where you’ve seen it
A retention triangle for a SaaS app: rows are signup months, columns are months since signup (0, 1, 2 …), and each cell is the percentage of that month's signups who were active then. A healthy product's curves flatten out instead of dropping towards zero.
Words you’ll hear
- Cohort
- Users grouped by their start period, such as signup month.
- Period offset
- How many periods after the cohort's start an activity happened (month 0, 1, 2…).
- Retention rate
- Distinct active users at offset k ÷ cohort size.
- Retention triangle
- The cohort × offset table; recent cohorts have fewer columns.
Visual diagram
Theory & example queries
Building it step by step
Step 1: each user's cohort, date_trunc('month', MIN(event_at)) (or their signup date). Step 2: each user's distinct active months. Step 3: join them and compute the offset in months. In PostgreSQL that's (EXTRACT(YEAR FROM age(active_month, cohort_month)) * 12 + EXTRACT(MONTH FROM age(active_month, cohort_month))), or compare year and month numbers directly.
Step 4: count distinct users per (cohort, offset) and divide by the cohort size from offset 0. Deduplicating to one row per user per month in step 2 is what stops a user with 50 events from counting 50 times.
| id | created_at | archived |
|---|---|---|
| 1 | 2024-11-20 | false |
| 2 | 2024-12-15 | false |
| 3 | 2026-01-05 | false |
WITH c AS ( SELECT user_id, date_trunc('month', MIN(event_at)) AS cohort FROM events GROUP BY 1 ), a AS ( SELECT DISTINCT user_id, date_trunc('month', event_at) AS m FROM events ), j AS ( SELECT c.cohort, ( EXTRACT( YEAR FROM a.m ) - EXTRACT( YEAR FROM c.cohort ) ) * 12 + EXTRACT( MONTH FROM a.m ) - EXTRACT( MONTH FROM c.cohort ) AS k, a.user_id FROM c JOIN a USING (user_id) )SELECT cohort, k, COUNT(*) AS users, ROUND( 100.0 * COUNT(*) / FIRST_VALUE(COUNT(*)) OVER ( PARTITION BY cohort ORDER BY k ), 1 ) AS pctFROM jGROUP BY cohort, kORDER BY cohort, k;PostgreSQL is the lesson baseline unless noted otherwise.
Read this line together with the surrounding statement as part of the same SQL expression.
Expected output4 sample rows
| cohort | k | users | pct |
|---|---|---|---|
| 2026-07-01 | 0 | 1000 | 100 |
| 2026-07-01 | 1 | 620 | 62 |
| 2026-07-01 | 2 | 510 | 51 |
| 2026-07-01 | 3 | 445 | 44.5 |
Note: Illustrative retention for one 1,000-user cohort; real percentages depend on events and month boundaries.
Key takeaway: Cohort per user, distinct active months, offset, then distinct users ÷ cohort size.
Definitions that change the answer
Decide what "active" means (any event, or a key action like a purchase), whether the cohort is the signup date or the first activity, and whether retention is "active in month k" (classic) or "active in month k or later" (unbounded). Different teams use different definitions, so state yours.
The newest cohorts haven't had time to reach later offsets, so their cells should be empty, not zero. The current month is also partial, which makes the latest column look worse than it is. Use a consistent timezone for date_trunc, or users near midnight shift between months.
Add WHERE date_trunc('month', event_at) < date_trunc('month', now()) to the activity step so incomplete months don't drag the latest column down.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Assign each user a cohort
Find each user's first activity (or signup) and truncate it to the cohort period.
date_trunc('month', MIN(event_at))
When to use it & trade-offs
What it is
Cohort retention groups users by when they started (the cohort, usually signup month) and measures what share of each cohort is still active 1, 2, 3 … periods later. In SQL it's a sequence of CTEs: each user's cohort, each user's active periods, the period offset between them, then distinct users per cohort and offset divided by cohort size.
Why it matters: Retention is the metric product teams care about most, because it shows whether people keep finding value. Cohort tables are a staple of data analyst and data scientist interviews, and they test several skills at once: grain, date arithmetic, distinct counting and joins.
When to reach for it
- Product health reviews and growth analysis
- Comparing the effect of onboarding changes across cohorts
- Analytics interview take-homes
When to avoid or be careful
- Counting events instead of distinct users
- Treating missing cells for recent cohorts as zero
- Mixing timezones when truncating dates
Retention definitions
Strengths: Easy to read; shows engagement in each period.
Watch out: A user who skips a month and returns looks churned for that month.
Strengths: Doesn't penalise gaps.
Watch out: Only ever decreases over time; less sensitive to recent changes.
Strengths: Fine-grained early signal.
Watch out: Noisy for small cohorts; needs daily data.
Interview signals & numbers to know
When this topic comes up
- “Monthly retention by signup cohort”
- “What percentage of users return after 30 days?”
- Cohort analysis
- Churn
- Retention curve
Benchmarks & rules of thumb
- 100%
- month-0 retention by definition
- 4
- CTE steps: cohort, activity, offset, rate
- 1 row
- per user per month after deduplication
Common mistakes & follow-ups
Common interview mistakes
- Counting rows in the joined table without deduplicating to user-month, inflating retention.
- Using signup month for some users and first-event month for others.
- Including the partial current month and concluding retention dropped.
Likely interviewer follow-ups
- How would you compute D1, D7 and D30 retention instead of monthly?
- How would you compare retention for users acquired from different channels?
- What's the difference between classic and unbounded retention?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Multi-Step Cohort & Retention Analysis Using CTEs with hands-on SQL practice and interview Q&A.