SQL for analysis · mid
Cohorts, retention and active users
A cohort table groups users by signup period and shows what share return in each later period. The share must divide by the cohort size, use decimals, and leave unfinished periods blank. DAU, MAU and stickiness need one row per user per day first.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Cohort = DATE_TRUNC('week', signup_at). Week number is whole 7-day blocks since signup, or the calendar-week difference. Say which one you use and why.
- Start from users and LEFT JOIN delivered orders, so a cohort with no orders still appears. Use COUNT(DISTINCT user_id), so a user with five orders in one week counts once.
- Pivot with COUNT(DISTINCT CASE WHEN week_no = 1 THEN user_id END) per column. Divide by the cohort size, not by the number of users who ordered.
- In Postgres, SQL Server, Redshift and SQLite, integer divided by integer is integer division, so 0.4 becomes 0. Use 100.0 * x / NULLIF(y, 0) or a cast. MySQL and BigQuery return decimals with /.
- A period that has not fully happened yet must be NULL (blank), not 0. Young cohorts otherwise look like a retention crash.
- Put the status filter (delivered) in the ON clause of the LEFT JOIN. In the WHERE clause it removes users who did not come back.
- Types of retention: classic (active in week N), rolling or unbounded (active in week N or later), and range retention.
- DAU: COUNT(DISTINCT user_id) per day on a table with one row per user per day. A 30-day MAU needs a calendar of days joined on activity_day BETWEEN day - 29 AND day, because most engines do not allow COUNT(DISTINCT) as a window function.
- Stickiness is DAU divided by MAU. It can rise only because MAU fell, so check both parts.
The red pen
Common traps: mistake → fix
Mistake: MAU is the average of 30 daily DAUs
Fix: MAU counts each user once over the period; averaging DAU gives something else.
Mistake: Retention of 0% everywhere means nobody returns
Fix: in Postgres it is often integer division, plus cohorts that are too young.
Mistake: Divide by users who ordered
Fix: that always looks like 100%; divide by the cohort size.
Easy to hard
Questions interviewers ask, easy to hard
- What is a retention cohort table?
- How do you build week 1 to week 4 retention in SQL?
- Why does a retention query show 0 in every row in Postgres?
- How do you compute a rolling 30-day MAU for every day?
- What is the difference between classic and rolling retention?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.