Cohort analysis in SQL: a retention triangle that holds up
Signup cohorts, activity windows, the retention triangle in one tested query for PostgreSQL and ClickHouse, and the mistakes that quietly inflate or sink the numbers.
A cohort retention query in SQL does three things: it assigns every user to a cohort (usually the month they signed up), counts how many users from each cohort were active in each later period, and divides that count by the cohort’s original size. The result is the retention triangle: one row per cohort, one column per “month since signup”, and a staircase of empty cells where time has not happened yet. The basic query is a date_trunc(), a join and a count(DISTINCT ...), yet its numbers are often wrong in ways a chart hides. A cohort with no active users in a month disappears instead of showing 0%. The newest cohort looks like it collapsed because its month is only half over. Deleted accounts vanish and make old cohorts look loyal. Below is a small dataset, the full triangle as one query tested on PostgreSQL 18 and on ClickHouse 26.11, and each of those traps shown with real output.
What data does a cohort retention query need?
Two tables: one row per user with the date that defines the cohort, and one row per activity. Real event tables have many more columns, but these are the only ones the query touches.
CREATE TABLE users (
user_id int PRIMARY KEY,
signed_up_at timestamp NOT NULL,
deleted_at timestamp -- set when the account is closed
);
CREATE TABLE events (
user_id int NOT NULL,
event_at timestamp NOT NULL
);
INSERT INTO users VALUES
( 1, '2026-01-05 09:00', NULL),
( 2, '2026-01-12 14:30', NULL),
( 3, '2026-01-20 11:00', '2026-03-01 00:00'), -- churned, then deleted the account
( 4, '2026-01-31 22:15', NULL),
( 5, '2026-02-03 08:45', NULL),
( 6, '2026-02-14 16:20', '2026-04-02 00:00'), -- churned, then deleted the account
( 7, '2026-02-25 10:10', NULL),
( 8, '2026-03-02 13:00', NULL),
( 9, '2026-03-09 09:30', NULL),
(10, '2026-03-18 17:45', NULL),
(11, '2026-03-30 12:00', NULL),
(12, '2026-04-04 15:00', NULL),
(13, '2026-04-15 10:30', NULL),
(14, '2026-04-28 19:00', NULL),
(15, '2026-05-06 08:00', NULL),
(16, '2026-05-11 11:40', NULL);
INSERT INTO events VALUES
( 1, '2026-01-05 09:05'), ( 1, '2026-02-10 10:00'), ( 1, '2026-03-03 09:00'),
( 1, '2026-04-08 11:00'), ( 1, '2026-05-04 09:30'),
( 2, '2026-01-12 14:35'), ( 2, '2026-02-20 15:00'), ( 2, '2026-04-02 08:00'),
( 3, '2026-01-20 11:05'),
( 4, '2026-01-31 22:20'), ( 4, '2026-02-01 09:00'),
( 5, '2026-02-03 08:50'), ( 5, '2026-03-05 12:00'), ( 5, '2026-05-12 10:00'),
( 6, '2026-02-14 16:25'),
( 7, '2026-02-25 10:15'), ( 7, '2026-03-28 18:00'), ( 7, '2026-05-02 09:00'),
( 8, '2026-03-02 13:05'), ( 8, '2026-04-01 10:00'), ( 8, '2026-05-06 14:00'),
( 9, '2026-03-09 09:35'), ( 9, '2026-04-20 16:00'),
(10, '2026-03-18 17:50'),
(11, '2026-03-30 12:05'), (11, '2026-04-02 09:00'),
(12, '2026-04-04 15:05'), (12, '2026-05-10 10:00'),
(13, '2026-04-15 10:35'),
(14, '2026-04-28 19:05'),
(15, '2026-05-06 08:05'), (15, '2026-05-08 13:00'),
(16, '2026-05-11 11:45');
Sixteen users in five monthly cohorts, January to May 2026, with data loaded up to the end of 19 May, so May is still in progress. Two choices are baked in; make them on purpose in your own data. The cohort is the signup date, not the first event. And “active” means any event, where in practice you usually want a meaningful action (a query run, an order placed) rather than a login, filtered in the events part of the query.
How do you write the basic cohort query?
The textbook version: truncate the signup to a month, compute how many calendar months each event is after the cohort month, and count distinct users per cell.
WITH cohorts AS (
SELECT user_id, date_trunc('month', signed_up_at)::date AS cohort_month
FROM users
),
activity AS (
SELECT DISTINCT
c.cohort_month,
e.user_id,
((extract(year FROM e.event_at) - extract(year FROM c.cohort_month)) * 12
+ extract(month FROM e.event_at) - extract(month FROM c.cohort_month))::int AS month_number
FROM events e
JOIN cohorts c USING (user_id)
)
SELECT cohort_month, month_number, count(*) AS active_users
FROM activity
GROUP BY cohort_month, month_number
ORDER BY cohort_month, month_number;
| cohort_month | month_number | active_users |
|---|---|---|
| 2026-02-01 | 0 | 3 |
| 2026-02-01 | 1 | 2 |
| 2026-02-01 | 3 | 2 |
(The February rows of the output.) The DISTINCT matters: user 15 has two events in May and would otherwise count twice. Counting events instead of users is how cohort charts end up above 100%.
Note what is missing: February has no row for month 2. Nobody from that cohort was active in April, so there is nothing to group. A pivot shows a blank cell, and a line chart draws straight from month 1 to month 3, hiding the gap. As with any time series, generate the grid first, then join activity onto it.
How do you build the retention triangle in one query?
This version adds three things to the basic query: a grid of every cohort and month that has started, a completeness flag for each cell, and a pivot into the triangle shape. It runs as is on PostgreSQL.
WITH params AS (
SELECT date '2026-05-20' AS as_of -- events are complete up to, not including, this date
),
cohorts AS (
SELECT user_id, date_trunc('month', signed_up_at)::date AS cohort_month
FROM users
),
cohort_size AS (
SELECT cohort_month, count(*) AS cohort_users
FROM cohorts
GROUP BY cohort_month
),
activity AS ( -- one row per user per active month
SELECT DISTINCT
c.cohort_month,
e.user_id,
((extract(year FROM e.event_at) - extract(year FROM c.cohort_month)) * 12
+ extract(month FROM e.event_at) - extract(month FROM c.cohort_month))::int AS month_number
FROM events e
JOIN cohorts c USING (user_id)
WHERE e.event_at >= c.cohort_month
),
grid AS ( -- every cohort x month that has started, zeros included
SELECT s.cohort_month, s.cohort_users, n AS month_number,
s.cohort_month + make_interval(months => n + 1) <= p.as_of AS is_complete
FROM cohort_size s
CROSS JOIN params p
CROSS JOIN generate_series(0, 23) AS n
WHERE s.cohort_month + make_interval(months => n) < p.as_of
),
cells AS (
SELECT g.cohort_month, g.cohort_users, g.month_number, g.is_complete,
count(a.user_id) AS active_users
FROM grid g
LEFT JOIN activity a
ON a.cohort_month = g.cohort_month AND a.month_number = g.month_number
GROUP BY g.cohort_month, g.cohort_users, g.month_number, g.is_complete
)
SELECT cohort_month,
cohort_users,
max(round(100.0 * active_users / cohort_users)) FILTER (WHERE month_number = 0 AND is_complete) AS m0,
max(round(100.0 * active_users / cohort_users)) FILTER (WHERE month_number = 1 AND is_complete) AS m1,
max(round(100.0 * active_users / cohort_users)) FILTER (WHERE month_number = 2 AND is_complete) AS m2,
max(round(100.0 * active_users / cohort_users)) FILTER (WHERE month_number = 3 AND is_complete) AS m3
FROM cells
GROUP BY cohort_month, cohort_users
ORDER BY cohort_month;
| cohort_month | cohort_users | m0 | m1 | m2 | m3 |
|---|---|---|---|---|---|
| 2026-01-01 | 4 | 100 | 75 | 25 | 50 |
| 2026-02-01 | 3 | 100 | 67 | 0 | |
| 2026-03-01 | 4 | 100 | 75 | ||
| 2026-04-01 | 3 | 100 | |||
| 2026-05-01 | 2 |
Read it row by row: of the four users who signed up in January, 75% came back in February, 25% in March and 50% in April. Read it column by column to compare cohorts at the same age: month-1 retention was 75%, 67% and 75% for the three cohorts old enough to have a complete month 1.
The pieces worth understanding:
cohort_sizecomes fromusers, notevents. The denominator is everyone who entered the cohort, including users who never came back.gridis the spine. It keeps every cohort and month that has started, so February month 2 is a cell with 0 users instead of a missing row.WHERE e.event_at >= c.cohort_monthdiscards events dated before the cohort started (imported history, backfills). If many rows hit it, your cohort date is the wrong anchor.FILTERwithmax()pivots the long result into columns.FILTERworks in PostgreSQL, but not every engine supports it;max(CASE WHEN month_number = 1 AND is_complete THEN ... END)is the portable spelling. Add one column per month you want to display.
For anything beyond a few thousand users, run this over a pre-aggregated table with one row per user per active month instead of the raw events table. The cohort logic stays identical, and the expensive DISTINCT happens once, upstream.
Why do partial periods make the newest cohort look terrible?
Drop the AND is_complete from the pivot and add a month 4 column, and the same data produces this:
| cohort_month | cohort_users | m0 | m1 | m2 | m3 | m4 |
|---|---|---|---|---|---|---|
| 2026-01-01 | 4 | 100 | 75 | 25 | 50 | 25 |
| 2026-02-01 | 3 | 100 | 67 | 0 | 67 | |
| 2026-03-01 | 4 | 100 | 75 | 25 | ||
| 2026-04-01 | 3 | 100 | 33 | |||
| 2026-05-01 | 2 | 100 |
Every cell on the last diagonal is May, which has only 19 days of data. April’s month 1 at 33% looks like a collapse next to 75% and 67%, but it measures an unfinished month. February’s month 3 at 67% is just as partial, and the May cohort is still growing.
The is_complete flag counts a cell only when its whole month is before as_of. Set as_of in one place to the first day your data is not yet complete, not to now(): if your pipeline lands yesterday’s data at 06:00, now() at 05:00 makes yesterday look empty. Product analytics tools handle this the same way: Amplitude’s retention chart, for example, marks results for days with incomplete data with an asterisk. In SQL, a NULL is the honest equivalent of the asterisk, because it cannot be averaged into a cohort benchmark by accident.
How does survivor bias distort cohort retention?
Many users tables do not keep closed accounts, or every query against them carries WHERE deleted_at IS NULL out of habit. Add that filter to the cohorts CTE and run the triangle again:
| cohort_month | cohort_users | m0 | m1 | m2 | m3 |
|---|---|---|---|---|---|
| 2026-01-01 | 3 | 100 | 100 | 33 | 67 |
| 2026-02-01 | 2 | 100 | 100 | 0 | |
| 2026-03-01 | 4 | 100 | 75 | ||
| 2026-04-01 | 3 | 100 | |||
| 2026-05-01 | 2 |
January and February month-1 retention jump from 75% and 67% to a perfect 100%. Users 3 and 6 churned after one visit and later deleted their accounts, so they left the denominator. The bias is not random: the people who delete accounts are mostly the ones who left, and older cohorts have had longer to do it. Old cohorts look progressively more loyal than they were, which reads as “retention is getting worse” when it may not be.
The same distortion has other sources:
- Hard deletes for privacy requests. Keep an anonymized row (an ID and a signup date are enough) or snapshot cohort sizes when each cohort closes.
- Cohorts built from a current-customers table or CRM export, which only contain people who stayed.
- Merged accounts, where the surviving record keeps the later signup date.
- The first cohort in the data. If event history starts in January, a first-event cohort for January absorbs every pre-existing user and looks like a record acquisition month.
One test catches all of them: a cohort’s size should never change after its month ends. Store cohort_size and compare it run over run.
Calendar months or rolling 30-day windows?
The query above uses calendar months: any February event is “month 1” for a January signup. That matches monthly reporting but flatters late-month signups. User 4 signed up at 22:15 on 31 January and came back the next morning: month-1 retention in calendar terms, day 1 in elapsed time.
The alternative is a rolling window per user: period 0 is days 0 to 29 after signup, period 1 is days 30 to 59, and so on. Each user’s clock starts at their own signup, so a user is only eligible for period N once their own period N has ended, and the denominator varies by cell:
WITH params AS (
SELECT date '2026-05-20' AS as_of
),
cohorts AS (
SELECT user_id,
date_trunc('month', signed_up_at)::date AS cohort_month,
signed_up_at::date AS signup_date
FROM users
),
activity AS ( -- period n = days 30n to 30n+29 after signup
SELECT DISTINCT e.user_id, (e.event_at::date - c.signup_date) / 30 AS period
FROM events e
JOIN cohorts c USING (user_id)
WHERE e.event_at::date >= c.signup_date
),
eligible AS ( -- a user counts only once their window has closed
SELECT c.cohort_month, c.user_id, n AS period
FROM cohorts c
CROSS JOIN params p
CROSS JOIN generate_series(0, 23) AS n
WHERE c.signup_date + 30 * (n + 1) <= p.as_of
)
SELECT el.cohort_month,
el.period,
count(*) AS eligible_users,
count(a.user_id) AS active_users,
round(100.0 * count(a.user_id) / count(*)) AS retention_pct
FROM eligible el
LEFT JOIN activity a
ON a.user_id = el.user_id AND a.period = el.period
WHERE el.period BETWEEN 1 AND 3
GROUP BY el.cohort_month, el.period
ORDER BY el.cohort_month, el.period;
| cohort_month | period | eligible_users | active_users | retention_pct |
|---|---|---|---|---|
| 2026-01-01 | 1 | 4 | 2 | 50 |
| 2026-01-01 | 2 | 4 | 1 | 25 |
| 2026-01-01 | 3 | 3 | 1 | 33 |
| 2026-02-01 | 1 | 3 | 2 | 67 |
| 2026-02-01 | 2 | 2 | 0 | 0 |
| 2026-03-01 | 1 | 3 | 2 | 67 |
January’s month-1 retention drops from 75% to 50%, because user 4’s next-morning visit now counts as period 0. March drops from 75% to 67% for the same reason (user 11 signed up on 30 March and returned on 2 April), and its denominator is 3, not 4, because user 11’s second 30-day window has not closed yet. Same users, same events, materially different answer.
Neither definition is wrong. Calendar months fit board reporting; rolling windows fit product questions and treat late-month signups fairly. What is wrong is mixing them under one label, “month 1 retention”, across a dashboard and a product analytics tool. Amplitude, for instance, lets you choose between 24-hour windows and strict calendar dates, so check which one any tool you compare against is using.
Exact-period or “on or after” retention?
Every number so far is exact-period retention: was the user active in month N? The other common definition, called “Return On or After” in Amplitude (formerly “Unbounded”), asks whether the user was active in month N or any later month. In SQL, it compares each user’s last active month with N:
WITH cohorts AS (
SELECT user_id, date_trunc('month', signed_up_at)::date AS cohort_month FROM users
),
last_seen AS (
SELECT c.cohort_month, c.user_id,
max((extract(year FROM e.event_at) - extract(year FROM c.cohort_month)) * 12
+ extract(month FROM e.event_at) - extract(month FROM c.cohort_month))::int AS last_month_number
FROM cohorts c JOIN events e USING (user_id)
GROUP BY c.cohort_month, c.user_id
)
SELECT cohort_month,
count(*) AS cohort_users,
round(100.0 * count(*) FILTER (WHERE last_month_number >= 1) / count(*)) AS m1_or_later,
round(100.0 * count(*) FILTER (WHERE last_month_number >= 2) / count(*)) AS m2_or_later
FROM last_seen
GROUP BY cohort_month
ORDER BY cohort_month;
The February cohort shows 67% for “month 2 or later”, against 0% exact-period month-2 retention, because two of its users skipped April and came back in May. “On or after” curves are smoother and never rise as N grows, which suits products used occasionally. On live data they have a cost: a recent cohort’s “month 2 or later” can only rise as time passes, so it is understated until the data window is long enough. (This short query sizes cohorts from events, so it misses users with no events; the triangle query does not.) Pick one definition per metric, name it, and never plot both on one axis.
How do you write cohort retention in ClickHouse?
The triangle query ports to ClickHouse with function renames, but ClickHouse also has a built-in aggregate for this, retention(). It takes 1 to 32 conditions and returns an array of 0s and 1s; per the documentation, conditions after the first “apply in pairs”, so element 2 is 1 if conditions 1 and 2 are both true, element 3 if 1 and 3 are. Get one array per user, then sum per cohort with sumForEach:
SELECT
cohort_month,
count() AS cohort_users,
sumForEach(r) AS active_by_month,
arrayMap(
(x, i) -> if(addMonths(cohort_month, i) <= toDate('2026-05-20'),
round(100 * x / cohort_users), NULL),
active_by_month, arrayEnumerate(active_by_month)
) AS retention_pct
FROM
(
SELECT
u.user_id,
toStartOfMonth(u.signed_up_at) AS cohort_month,
retention(
dateDiff('month', cohort_month, e.event_at) = 0,
dateDiff('month', cohort_month, e.event_at) = 1,
dateDiff('month', cohort_month, e.event_at) = 2,
dateDiff('month', cohort_month, e.event_at) = 3
) AS r
FROM users AS u
INNER JOIN events AS e ON e.user_id = u.user_id
GROUP BY u.user_id, cohort_month
)
GROUP BY cohort_month
ORDER BY cohort_month;
| cohort_month | cohort_users | active_by_month | retention_pct |
|---|---|---|---|
| 2026-01-01 | 4 | [4,3,1,2] | [100,75,25,50] |
| 2026-02-01 | 3 | [3,2,0,2] | [100,67,0,NULL] |
| 2026-03-01 | 4 | [4,3,1,0] | [100,75,NULL,NULL] |
| 2026-04-01 | 3 | [3,1,0,0] | [100,NULL,NULL,NULL] |
| 2026-05-01 | 2 | [2,0,0,0] | [NULL,NULL,NULL,NULL] |
The results match the PostgreSQL triangle cell for cell. Three things to know before you rely on it:
retention()returns 0 for months that have not happened. April’sactive_by_monthis[3,1,0,0]. Without thearrayMapmask those zeros read as “nobody came back”, the partial-period trap at its most misleading.- Everything hinges on the first condition. A user with no month-0 event gets all zeros, even if they were active later. Make the first condition something every cohort member satisfies.
- The
INNER JOINdrops users with no events, shrinkingcohort_users. Every user here has a signup event; if yours do not, size cohorts fromusersseparately.
dateDiff('month', ...) counts calendar month boundaries crossed, so 31 January to 1 February is 1, matching the PostgreSQL version. On a large events table, order it by (user_id, event_at) and pre-filter the date range. If you are joining users and events at scale, the ClickHouse JOIN performance guide covers which side to put where.
The decisions to write down before you share a cohort chart
| Decision | Options | What it changed in this data |
|---|---|---|
| Cohort anchor | Signup date, first event, first purchase | Events before signup are a sign the anchor is wrong |
| Active means | Any event, or a key action | Login-only activity inflates every cell |
| Period type | Calendar months, rolling 30-day windows | January month 1: 75% vs 50% |
| Period rule | Exact period, or on or after | February month 2: 0% vs 67% |
| Partial periods | Mask, or show and flag | April month 1 looked like 33% |
| Deleted users | Keep in the denominator, or drop | January month 1 inflated from 75% to 100% |
Each row is a short SQL change and a large change in the answer. The MRR and churn post makes the same point about revenue retention, which is this query with money in place of user counts.
Keep one definition of retention
The query is the easy part. Every new dashboard, notebook and AI-generated query is a fresh chance to pick a different row from that table, until “month 1 retention” means three things in three places. The durable fix is to define the cohort model and retention metric once, review them like code, and have every chart and assistant ask for them by name. That is what a semantic layer is for.
Goni is one way to do that on ClickHouse. It is one AI platform for the data stack: ELT connectors, a ClickHouse warehouse, a YAML semantic layer where models and metrics are defined once and models carry tests, and BI (a SQL IDE, dashboards with cohort and heatmap chart types, alerts and scheduled reports) plus AI Q&A that answers from the same metric definitions and shows the compiled SQL. The trade-off: ClickHouse is the only warehouse it queries, so it suits teams willing to run their analytics there. You can try it with the 14-day free trial.
FAQ
What is cohort analysis in SQL?
Cohort analysis groups users by a shared starting event, usually the signup month, and tracks what share of each group is active in each later period. In SQL that means assigning a cohort per user, computing each activity’s period offset from the cohort start, counting distinct users per cohort and period, and dividing by the cohort’s original size.
How do you calculate retention rate in SQL?
Divide the number of distinct cohort users active in period N by the number of users who entered the cohort. Take the denominator from the users table, not from events, so users who never returned still count. Generate every cohort and period combination first, so periods with no activity show 0% instead of disappearing.
What is a retention triangle?
A retention triangle is a table with one row per cohort and one column per period since the cohort started. Older cohorts have more completed periods, so the filled cells form a staircase or triangle. Reading down a column compares cohorts at the same age; reading across a row shows one cohort’s decay over time.
Should incomplete periods appear in a cohort table?
Not as ordinary numbers. A period that is still in progress understates retention, and averaging it into benchmarks drags them down. Return NULL for any cell whose period has not fully ended before your data’s completeness date, or show it in a visibly different style. Never compute completeness from the current time if your pipeline lags.
What causes survivor bias in cohort analysis?
Survivor bias appears when users who left are removed from the cohort’s denominator: hard-deleted accounts, filters like deleted_at IS NULL, or cohorts built from a current-customers table. Churned users are the ones most likely to be removed, so old cohorts look more loyal than they were. A cohort’s size should never change once its month ends.