How would you build a cohort retention grid in SQL from first-activity periods?
Role: Data Scientist
Category: Data Manipulation (SQL/Python)
Difficulty: medium
Interview Round: Other
How would you assemble a cohort or retention grid in SQL? Explain the query technique for grouping entities by first-activity period and measuring activity in later periods.
Assume an `events` table with one row per user action that holds at least `user_id` and `event_date`, and a monthly grid where rows are cohorts and columns are months since the cohort started.
```hint Compute the anchor once
Work out each user's first period in its own step before you look at the rest of their activity rows.
```
```hint What goes in a cell
A user can act many times in one month. Decide what each cell counts and what its denominator is.
```
### Clarifying Questions to Ask
- What counts as activity: any event, or a qualifying action such as a login or a purchase?
- Is the cohort the month of first activity, or a signup date stored in a separate users table?
- Should a cell count users active in exactly that period, or users active in that period or any later one (rolling retention)?
- Do you want raw counts, percentages of the cohort, or both, and in long or wide (pivoted) form?
### What a Strong Answer Covers
- Derives each entity's cohort period once from its first activity and joins it back to the activity rows.
- Computes an integer period offset that stays correct across year boundaries, with 0 as the cohort period.
- Counts distinct entities per cohort and offset, and converts counts to rates using the cohort size as the denominator.
- Shapes the long result into a grid and handles right-censoring of recent cohorts, the incomplete current period, and zero cells versus periods that cannot be observed yet.
### Follow-up Questions
- How would you change the query for weekly cohorts, or for rolling retention?
- How would you keep this fast on a table with billions of events?
- If the cohort comes from a signup date in a users table, what changes, and why might period 0 no longer be 100%?
- How would you report revenue retention per cohort instead of user counts?
Overview: Explain how to build a cohort retention grid in SQL by grouping users on their first-activity month and tracking them in later months. Tests period-offset math, distinct counting, retention rates, pivoting, and handling recent cohorts that have not had time to mature.