Kodewick
Start learning →
Retention and cohorts8 / 12

Retention and cohorts

Lesson 8 of 12 · Part 3 · Analysing users · about 20 minutes

Cohorts: first find each person's first order month with MIN(month), then work out which month after it each purchase falls in with TIMESTAMPDIFF(MONTH, first month, this month), and finally build a table with one row per group using COUNT(DISTINCT CASE WHEN k = 1 THEN user_id END). Cells whose data hasn't arrived yet should be empty, not 0.

The boss says: "Getting a new customer costs us money in ads. Do people who bought once ever come back?" That's retention. This lesson starts with one simple number, then builds the most classic table in data analysis: the cohort table.

Repeat purchase rate

In this step you work out the simplest retention measure: of the people who bought, how many bought more than once. First count each person's orders, then count how many people have at least 2:

main.sql
1WITH counts AS (2    SELECT user_id, COUNT(*) AS n3    FROM orders4    WHERE status = 'paid'5    GROUP BY user_id6)7SELECT COUNT(*) AS buyers,8    SUM(CASE WHEN n >= 2 THEN 1 ELSE 0 END) AS repeat_buyers,9    ROUND(100 * SUM(CASE WHEN n >= 2 THEN 1 ELSE 0 END) / COUNT(*), 1) AS repeat_pct10FROM counts;
Output
buyersrepeat_buyersrepeat_pct
312993.5
1 row

Of 31 buyers, 29 bought more than once, a repeat purchase rate of 93.5%. This little shop's customers are very loyal. But the repeat purchase rate is just one number. It can't tell you whether new customers are coming back less and less. For that, you need cohorts.

Choose one

Why count each person's orders in WITH first, instead of writing SUM(CASE WHEN COUNT(*) >= 2 …) straight on orders?

Group by the month of the first order

In this step you split customers into cohorts: people whose first purchase was in the same month belong to the same group, just like a school calls everyone who started in the same year "the class of 2025". First find the month of each person's first purchase:

main.sql
1WITH monthly AS (2    SELECT DISTINCT user_id,3        DATE_SUB(order_date, INTERVAL DAY(order_date) - 1 DAY) AS month_start4    FROM orders5    WHERE status = 'paid'6),7firsts AS (8    SELECT user_id, MIN(month_start) AS cohort9    FROM monthly10    GROUP BY user_id11)12SELECT DATE_FORMAT(cohort, '%Y-%m') AS cohort, COUNT(*) AS users13FROM firsts14GROUP BY cohort15ORDER BY cohort;
Output
cohortusers
2025-011
2025-036
2025-055
2025-062
2025-075
2025-082
2025-092
2025-105
2025-112
2025-121
10 rows

monthly is "who bought in which month", one row per person per month (the "move back to the 1st" trick from lesson 6). firsts takes each person's earliest month. The March group has 6 people, and May, July and October have 5 each.

Fill inTap one to fill a blank; tap a blank to take it back

Fill in a function to find the month of each person's last purchase.

1SELECT user_id, (month_start) AS last_month2FROM monthly3GROUP BY user_id;

Which month they came back

In this step you give every purchase a number: which month after the first order it falls in. Join monthly with firsts, and use TIMESTAMPDIFF(MONTH, first month, this month):

main.sql
1WITH monthly AS (2    SELECT DISTINCT user_id,3        DATE_SUB(order_date, INTERVAL DAY(order_date) - 1 DAY) AS month_start4    FROM orders5    WHERE status = 'paid'6),7firsts AS (8    SELECT user_id, MIN(month_start) AS cohort9    FROM monthly10    GROUP BY user_id11)12SELECT m.month_start, TIMESTAMPDIFF(MONTH, f.cohort, m.month_start) AS k13FROM monthly AS m14JOIN firsts AS f ON f.user_id = m.user_id15WHERE m.user_id = 616ORDER BY m.month_start;
Output
month_startk
2025-03-010
2025-04-011
2025-07-014
2025-08-015
2025-11-018
2025-12-019
6 rows

Felipe first bought in March, so k = 0. He bought again in April, which is month 1, and he also came back in months 4, 5, 8 and 9. With k, you can line up any group against any other: "how many people are left in month 1".

monthly
user_idmonth_startk
62025-03-010
62025-04-011
62025-07-014
122025-03-010
122025-04-011
Every purchase becomes "month k after the first order"
Choose one

Someone first bought on May 3 and bought again on May 28. What's the k of the second purchase?

The cohort table

In this step you turn it into a table: one row per group, one column each for months 1, 2 and 3, and in each cell the number of people still buying that month. It's the "rows into columns" trick from lesson 3, except this time you count different people, so you use COUNT(DISTINCT CASE …):

main.sql
1WITH monthly AS (2    SELECT DISTINCT user_id,3        DATE_SUB(order_date, INTERVAL DAY(order_date) - 1 DAY) AS month_start4    FROM orders5    WHERE status = 'paid'6),7firsts AS (8    SELECT user_id, MIN(month_start) AS cohort9    FROM monthly10    GROUP BY user_id11),12activity AS (13    SELECT m.user_id, f.cohort, TIMESTAMPDIFF(MONTH, f.cohort, m.month_start) AS k14    FROM monthly AS m15    JOIN firsts AS f ON f.user_id = m.user_id16)17SELECT DATE_FORMAT(cohort, '%Y-%m') AS cohort,18    COUNT(DISTINCT user_id) AS users,19    COUNT(DISTINCT CASE WHEN k = 1 THEN user_id END) AS m1,20    COUNT(DISTINCT CASE WHEN k = 2 THEN user_id END) AS m2,21    COUNT(DISTINCT CASE WHEN k = 3 THEN user_id END) AS m322FROM activity23GROUP BY cohort24ORDER BY cohort;
Output
cohortusersm1m2m3
2025-011010
2025-036241
2025-055241
2025-062010
2025-075133
2025-082211
2025-092011
2025-105430
2025-112200
2025-121000
10 rows

Read a row across, and you get one group's story: the May group has 5 people, 2 came back the next month, and 4 came back in month 2. Read a column down, and you see how different groups did at the same stage: in the October group, 4 people came back in month 1, better than any group before it.

Exercise 1

Next-month retention

Look only at the groups from July on, and work out each group's month-1 retention rate (people who came back ÷ people in the group × 100, rounded to a whole number). Three columns: cohort (written like 2025-07), users and m1_pct, sorted by cohort.

It should print
cohortusersm1_pct
2025-07520
2025-082100
2025-0920
2025-10580
2025-112100
2025-1210
6 rows
exercise1.sql
1WITH monthly AS (2    SELECT DISTINCT user_id,3        DATE_SUB(order_date, INTERVAL DAY(order_date) - 1 DAY) AS month_start4    FROM orders5    WHERE status = 'paid'6),7firsts AS (8    SELECT user_id, MIN(month_start) AS cohort9    FROM monthly10    GROUP BY user_id11),12activity AS (13    SELECT m.user_id, f.cohort, TIMESTAMPDIFF(MONTH, f.cohort, m.month_start) AS k14    FROM monthly AS m15    JOIN firsts AS f ON f.user_id = m.user_id16)17SELECT DATE_FORMAT(cohort, '%Y-%m') AS cohort18FROM activity19GROUP BY cohort20ORDER BY cohort;
Output
Press Run or Ctrl+Enter

In small groups, the percentages jump around a lot: 2 out of 2 coming back is already 100%. When you look at retention rates, always keep the group size next to them.

Months that haven't happened yet

In this step you look at the part of a cohort table that's easiest to misread. The data only goes up to December. For the December group, "month 1" is next January, which hasn't happened yet, but the table says 0, which looks like "nobody came back".

The fix: if that month hasn't arrived yet, don't count it, and leave the cell as NULL. Month k is DATE_ADD(cohort, INTERVAL k MONTH), and you only count it when that's no later than the last month, December:

Choose oneA wrong guess is fine

With this fix, what are m1 and m2 for the November group?

1WITH monthly AS (2    SELECT DISTINCT user_id,3        DATE_SUB(order_date, INTERVAL DAY(order_date) - 1 DAY) AS month_start4    FROM orders5    WHERE status = 'paid'6),7firsts AS (8    SELECT user_id, MIN(month_start) AS cohort9    FROM monthly10    GROUP BY user_id11),12activity AS (13    SELECT m.user_id, f.cohort, TIMESTAMPDIFF(MONTH, f.cohort, m.month_start) AS k14    FROM monthly AS m15    JOIN firsts AS f ON f.user_id = m.user_id16)17SELECT DATE_FORMAT(cohort, '%Y-%m') AS cohort,18    CASE WHEN DATE_ADD(cohort, INTERVAL 1 MONTH) <= '2025-12-01'19        THEN COUNT(DISTINCT CASE WHEN k = 1 THEN user_id END) END AS m1,20    CASE WHEN DATE_ADD(cohort, INTERVAL 2 MONTH) <= '2025-12-01'21        THEN COUNT(DISTINCT CASE WHEN k = 2 THEN user_id END) END AS m222FROM activity23WHERE cohort >= '2025-10-01'24GROUP BY cohort25ORDER BY cohort;

What you learned

  • Repeat purchase rate: first count each person's orders, then count the people with at least 2. When an aggregate takes two steps, put the first step in WITH.
  • Cohorts: group people by the month of their first purchase. MIN(month) is the first order month.
  • TIMESTAMPDIFF(MONTH, first month, this month) is month k. Several purchases in one month count only once, so first take DISTINCT user_id, month.
  • The cohort table: COUNT(DISTINCT CASE WHEN k = 1 THEN user_id END), one column per k.
  • Percentages in small groups swing wildly, so write the group size next to them.
  • Months that haven't happened yet should show NULL, not 0.
Practise what this lesson taught#020AVG(n >= 2)Repeat buyersBasic#017LEFT JOIN + AVG()Next-day retentionBasic#018LEFT JOIN + COUNT(col)Retention by sign-up dayBasicAll 50 SQL problems →