Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 75/ 160
04. Subqueries & Common Table Expressions (CTEs)

Multi-Step Cohort & Retention Analysis Using CTEs

Build cohort tables and retention curves with staged CTE transforms.

AdvancedCohort · Retention3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

The full query (PostgreSQL)Query example
1Input dataStart from the source rows or state that the statement sees.
events
3 rows
events sample rows
idcreated_atarchived
12024-11-20false
22024-12-15false
32026-01-05false
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1WITH2  c AS (3    SELECT4      user_id,5      date_trunc('month', MIN(event_at)) AS cohort6    FROM7      events8    GROUP BY9      110  ),11  a AS (12    SELECT DISTINCT13      user_id,14      date_trunc('month', event_at) AS m15    FROM16      events17  ),18  j AS (19    SELECT20      c.cohort,21      (22        EXTRACT(23          YEAR24          FROM25            a.m26        ) - EXTRACT(27          YEAR28          FROM29            c.cohort30        )31      ) * 12 + EXTRACT(32        MONTH33        FROM34          a.m35      ) - EXTRACT(36        MONTH37        FROM38          c.cohort39      ) AS k,40      a.user_id41    FROM42      c43      JOIN a USING (user_id)44  )45SELECT46  cohort,47  k,48  COUNT(*) AS users,49  ROUND(50    100.0 * COUNT(*) / FIRST_VALUE(COUNT(*)) OVER (51      PARTITION BY52        cohort53      ORDER BY54        k55    ),56    157  ) AS pct58FROM59  j60GROUP BY61  cohort,62  k63ORDER BY64  cohort,65  k;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/65
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output4 sample rows
Expected output
cohortkuserspct
2026-07-0101000100
2026-07-01162062
2026-07-01251051
2026-07-01344544.5

Note: Illustrative retention for one 1,000-user cohort; real percentages depend on events and month boundaries.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

Excluding the partial current month

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.

Key takeaway: State the definitions, and don't read missing cells as zero retention.
Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1CTE: cohorts

Assign each user a cohort

Find each user's first activity (or signup) and truncate it to the cohort period.

Focus at this step

date_trunc('month', MIN(event_at))

What to watch at this step
Grain
one row per user
Tip: use ← → to move between steps

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

Classic (active in month k)
Best for: Standard cohort triangles

Strengths: Easy to read; shows engagement in each period.

Watch out: A user who skips a month and returns looks churned for that month.

Unbounded (active in month k or later)
Best for: Products with irregular usage (travel, tax)

Strengths: Doesn't penalise gaps.

Watch out: Only ever decreases over time; less sensitive to recent changes.

Day-N retention (D1, D7, D30)
Best for: Mobile apps and consumer products

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?
Interview tip: Name the four steps and their grains before writing SQL, and state your definition of "active". Interviewers mostly score whether your counting is right, and the grains make that visible.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Data-Modifying CTEs (WITH deleted AS (DELETE ... RETURNING *))
Next topic
Funnel Conversion Analysis Queries with CTEs