Growth reports the share of each monthly signup cohort that came back and transacted in the following calendar month.
app_users holds signed_up_on; app_activity holds one row per active day. Using CTEs, return cohort_month, cohort_size, retained_users and retention_pct (retained ÷ cohort size × 100, rounded to 1 decimal).
Sample data
Table: app_users
12 row(s) · showing first 8
| user_idINT | user_emailTEXT | signed_up_onDATE |
|---|---|---|
| 1 | ira@example.in | 2026-01-05 |
| 2 | devansh@example.in | 2026-01-11 |
| 3 | nikhil@example.in | 2026-01-19 |
| 4 | mahima@example.in | 2026-01-26 |
| 5 | yusuf@example.in | 2026-02-03 |
| 6 | prerna@example.in | 2026-02-09 |
| 7 | sagar@example.in | 2026-02-17 |
| 8 | rhea@example.in | 2026-02-24 |
Table: app_activity
19 row(s) · showing first 8
| activity_idINT | user_idINT | active_onDATE |
|---|---|---|
| 1 | 1 | 2026-01-06 |
| 2 | 1 | 2026-02-14 |
| 3 | 2 | 2026-01-12 |
| 4 | 2 | 2026-02-02 |
| 5 | 3 | 2026-01-20 |
| 6 | 4 | 2026-01-27 |
| 7 | 4 | 2026-03-05 |
| 8 | 5 | 2026-02-04 |
app_users
- user_idINT
- user_emailTEXT
- signed_up_onDATE
app_activity
- activity_idINT
- user_idINT
- active_onDATE
- Step 1: In the `cohorts` CTE, bucket each user into their signup month with `DATE_TRUNC('month', signed_up_on)` cast back to `date`.
- Step 2: In the `retained` CTE, join activity to cohorts and keep only activity whose month equals the cohort month plus one month. `DISTINCT` collapses multiple active days into one retained user.
- Step 3: Left-join the cohort list to the retained list so cohorts with nobody returning still appear with zero.
- Step 4: `COUNT(*)` gives the cohort size while `COUNT(r.user_id)` ignores `NULL`s and therefore counts only retained users.
- Step 5: Compute the percentage as `COUNT(r.user_id) * 100.0 / COUNT(*)`. Multiplying by `100.0` forces numeric division instead of integer division; round to 1 decimal.
- Step 6: Group by `cohort_month` to produce one row per cohort.
WITH cohorts AS (
SELECT user_id,
DATE_TRUNC('month', signed_up_on)::date AS cohort_month
FROM app_users
),
retained AS (
SELECT DISTINCT c.user_id, c.cohort_month
FROM cohorts AS c
INNER JOIN app_activity AS a ON a.user_id = c.user_id
WHERE DATE_TRUNC('month', a.active_on)::date
= (c.cohort_month + INTERVAL '1 month')::date
)
SELECT c.cohort_month,
COUNT(*) AS cohort_size,
COUNT(r.user_id) AS retained_users,
ROUND(COUNT(r.user_id) * 100.0 / COUNT(*), 1) AS retention_pct
FROM cohorts AS c
LEFT JOIN retained AS r ON r.user_id = c.user_id
GROUP BY c.cohort_month;Learn the concept first
Stuck on CTEs? These free SQL lessons teach it step by step.
More CTEs questions
Practising alone only goes so far — our live cohorts pair SQL depth with dashboards, agentic analytics projects and mock interviews.
Explore the program