SQL Interview & Case Lab
Back to Business SQL Patterns

Cohort Retention Analysis in Pure SQL

Building the retention triangle from raw events — one query, no Python. FIND_VIDEO: search 'cohort retention SQL window functions' — recommended channel: EverSQL / Mode Analytics. Aim for 12 min or under.

19 minutesVideo LessonPDF notes
🎯 Free Guest Mode: You are learning for free. Sign in to save your completion progress and quiz answers.
Loading progress...

Key moments

  1. Cohort Analysis Fundamentals — Introduces cohorts as user groups sharing common characteristics like signup month to track retention over time.
  2. Table Schema and Relationship — Explains the schema structure of user signups and recurring user event logs.
  3. Date Normalization with DATE_FORMAT — Formats raw signup and event dates into standardized first-of-the-month dates.
  4. Building CTEs for Users and Events — Defines Common Table Expressions to stage cohort signups and normalized activity months.
  5. Joining Cohorts and Grouping Counts — Joins staged user cohorts with active events on user_id to count active users.
  6. Calculating Months with TIMESTAMPDIFF — Replaces DATEDIFF with TIMESTAMPDIFF to compute elapsed month offsets across retention periods.
  7. Interpreting Cohort Output — Reviews the resulting dataset showing retention drops across subsequent lifecycle months.
PDF notes

Frequently asked questions

Why normalize cohort dates to the first day of the month instead of just stripping the day?

Keeping a valid date structure like 'YYYY-MM-01' allows date comparison and difference functions like TIMESTAMPDIFF to work without returning nulls.

Why is the elapsed month index 0 for the first month?

When a user signs up and generates events in the same calendar month, the difference between identical cohort and activity months is 0.

Can user event dates precede the signup date in retention analysis?

No, event dates occur on or after signup, meaning month_since_signup will always be greater than or equal to zero.

How was this lesson?

Your feedback helps us refine explanations and catch bugs.