Skip to content

Cohorts and retention

Group users by the month they started, then count how many come back in each later month.

Practise: 10 questions

When you need it

"Monthly retention by signup cohort", "what share of users from January were still active in March", "how many weeks after signup do people buy", "churn". Words that signal it: "cohort", "retention", "returned", "still active", "N days after", "by signup month".

A cohort is a group defined by when something first happened. Retention asks how big that group still is at each later point.

The shape of the query

with cohort as (
  select user_id, date_trunc('month', signed_up_at)::date as cohort_month
  from users
),
activity as (
  select distinct user_id, date_trunc('month', occurred_at)::date as active_month
  from events
)
select c.cohort_month,
       (extract(year from age(a.active_month, c.cohort_month)) * 12
        + extract(month from age(a.active_month, c.cohort_month)))::int as months_since,
       count(distinct c.user_id) as active_users
from cohort c
join activity a on a.user_id = c.user_id and a.active_month >= c.cohort_month
group by 1, 2;

Step by step:

  1. Assign each user one cohort, from their first date.
  2. Reduce activity to one row per user per period. distinct stops a user who acts ten times counting ten times.
  3. Join them, and compute how many periods separate the cohort from the activity.
  4. Count distinct users per cohort and offset. Divide by the cohort size for a rate.
with cohort as (
  select user_id, date_trunc('month', signed_up_at)::date as cohort_month
  from users
),
activity as (
  select distinct user_id, date_trunc('month', occurred_at)::date as active_month
  from events
),
sizes as (
  select cohort_month, count(*) as cohort_size from cohort group by 1
)
select c.cohort_month,
       ((extract(year from a.active_month) - extract(year from c.cohort_month)) * 12
        + extract(month from a.active_month) - extract(month from c.cohort_month))::int as months_since,
       count(distinct c.user_id) as active_users,
       round(100.0 * count(distinct c.user_id) / s.cohort_size, 1) as pct_of_cohort
from cohort c
join sizes s on s.cohort_month = c.cohort_month
join activity a on a.user_id = c.user_id and a.active_month >= c.cohort_month
group by c.cohort_month, s.cohort_size, months_since
order by c.cohort_month, months_since;

Month 0 is the signup month itself. Its percent should be close to 100 if signing up counts as activity, and lower if the event table does not include the signup.

Traps interviewers look for

Variations

In other warehouses

Practise cohorts and retention