Esc

↑↓ moveEnter open

← All writing
SQL · Product AnalyticsPublished 8 November 20265 min readSajid Hasan Sifat

Cohort Retention Analysis in SQL: A Step-by-Step Guide

How to build a monthly cohort retention table from raw orders: define the cohort, pick the activity, write the SQL, read the triangle, and avoid the definition mistakes that make retention numbers wrong.

On this page9 sections · 5 min

“Are customers coming back?” is one of the most important questions a product or growth team can ask.

It is also one of the easiest to answer badly.

A single number like “our retention is 35%” hides almost everything that matters: which customers, coming back to do what, after how long, and is it getting better or worse?

A cohort retention table answers all of that at once. This guide builds one from raw orders, one step at a time, and explains how to read it without fooling yourself.

What a cohort is

A cohort is a group of users who share a starting point. The most common choice is the month of their first purchase.

Everyone who first bought in January is the January cohort. Everyone who first bought in February is the February cohort. Then, for each cohort, you ask: what share of them were active again one month later, two months later, three months later…?

The result looks like a triangle:

Cohort Users M0 M1 M2 M3
Jan 1,000 100% 32% 24% 21%
Feb 1,200 100% 35% 27% —
Mar 900 100% 30% — —
Apr 1,100 100% — — —

(Illustrative numbers.)

Read across a row to see how one cohort decays over time. Read down a column to see whether newer cohorts retain better or worse than older ones at the same age. That second view is where cohort tables earn their keep: a product change in March should show up as the March row behaving differently from January and February.

Step 0: write the definition down first

Before any SQL, agree on three things. Most retention arguments in companies are really disagreements about these:

  1. Who enters a cohort? First order ever? First completed order (excluding cancelled and refunded)? First order after signing up?
  2. What counts as “retained”? Placing any order? A completed order? Opening the app? Each gives a different number, and none is wrong — but they answer different questions.
  3. What is the time unit? Calendar months, or 30-day windows from each user’s first purchase? Calendar months are simpler and match business reporting. Rolling windows are fairer to users who joined late in a month.

In this guide: cohort = month of first completed order; retained = placed at least one completed order in that later calendar month.

Step 1: one row per user per active month

Start from an orders table with customer_id, order_date and status.

WITH activity AS (
  SELECT DISTINCT
    customer_id,
    DATE_TRUNC('month', order_date) AS activity_month
  FROM orders
  WHERE status = 'completed'
)

DISTINCT matters. A customer who ordered five times in March should count once for March. Without it, heavy users inflate retention.

Step 2: find each user’s cohort month

, cohorts AS (
  SELECT
    customer_id,
    MIN(activity_month) AS cohort_month
  FROM activity
  GROUP BY customer_id
)

Because activity already excludes cancelled orders, a customer whose only January order was cancelled will not be counted in January. That is the point of writing the definition first.

Step 3: how many months after the cohort is each activity?

, offsets AS (
  SELECT
    a.customer_id,
    c.cohort_month,
    (EXTRACT(YEAR  FROM a.activity_month) - EXTRACT(YEAR  FROM c.cohort_month)) * 12
  + (EXTRACT(MONTH FROM a.activity_month) - EXTRACT(MONTH FROM c.cohort_month)) AS month_number
  FROM activity a
  JOIN cohorts c USING (customer_id)
)

This works in PostgreSQL and most other databases. In BigQuery you can write DATE_DIFF(a.activity_month, c.cohort_month, MONTH) instead.

Month 0 is the cohort month itself, so it is always 100%.

Step 4: count users and divide by cohort size

, cohort_size AS (
  SELECT cohort_month, COUNT(*) AS users
  FROM cohorts
  GROUP BY cohort_month
)
SELECT
  o.cohort_month,
  s.users AS cohort_users,
  o.month_number,
  COUNT(DISTINCT o.customer_id) AS active_users,
  ROUND(100.0 * COUNT(DISTINCT o.customer_id) / s.users, 1) AS retention_pct
FROM offsets o
JOIN cohort_size s USING (cohort_month)
GROUP BY o.cohort_month, s.users, o.month_number
ORDER BY o.cohort_month, o.month_number;

This gives a long table: one row per cohort per month number. That is the best shape to store and to feed into a BI tool, which can pivot it into the triangle as a heatmap.

If you want the triangle directly in SQL, pivot with conditional aggregation:

SELECT
  cohort_month,
  MAX(cohort_users) AS users,
  MAX(CASE WHEN month_number = 1 THEN retention_pct END) AS m1,
  MAX(CASE WHEN month_number = 2 THEN retention_pct END) AS m2,
  MAX(CASE WHEN month_number = 3 THEN retention_pct END) AS m3
FROM retention_long          -- the result of the query above
GROUP BY cohort_month
ORDER BY cohort_month;

Step 5: read it honestly

A finished table is where analysis starts, not where it ends. A few habits keep the conclusions sound:

Ignore the incomplete edge. The most recent cohorts have had less time. If today is 10 November, the “October cohort, month 1” cell only contains ten days of November. Either drop the current month or label it clearly as partial.

Watch small cohorts. A cohort of 40 users moving from 30% to 38% is three people. Show the cohort size next to every row so nobody over-reads noise.

Separate the curve’s shape from its level. Most products lose many users in month 1, then flatten. A curve that keeps falling steeply and never flattens is a very different (and more worrying) problem than one that drops early and then holds.

Compare columns, not just rows. “Month-1 retention for cohorts since our onboarding change is 4 points higher” is the kind of sentence a product team can act on.

Check acquisition mix before celebrating. If a big campaign in March brought lower-intent users, the March cohort will retain worse even if the product improved. Splitting cohorts by acquisition channel often explains a surprising row.

Common mistakes

Counting orders instead of users. Retention is about people. Use COUNT(DISTINCT customer_id).

Using signup date when the question is about buyers (or the reverse). “Of people who signed up, how many ever buy?” is conversion. “Of people who bought once, how many buy again?” is repeat-purchase retention. Mixing them produces a number nobody can use.

Letting cancelled or test orders define cohorts. One filter in Step 1 prevents this; forgetting it quietly moves users into the wrong cohort.

Averaging percentages across cohorts. Averaging 30% (100 users) and 40% (2,000 users) to get 35% ignores size. Weight by cohort users, or recompute from the counts.

Calling a calendar-month table “30-day retention”. They are different definitions. Name the metric exactly what it measures.

Where to go next

Retention questions come up in almost every product analyst interview, usually as “how would you measure whether this feature improved retention?” The SQL is half the answer; the definition and the reading are the other half.

If you’re new to ROW_NUMBER, LAG and running totals, the companion guide on SQL window functions for data analysts pairs well with this one — many retention variations (days between orders, nth purchase) are easiest with window functions.

Thanks for reading

There’s more in the writing archive.

Browse all articles