Compute day-1 and day-7 retention per signup cohort

HardSQLPro

Why it matters D1 and D7 retention are the first numbers investors and product teams ask for in any consumer AI app.

Retention says if people come back. Day-1 retention is the share of a cohort active the day after signup, day-7 is the share active exactly a week later. Activity logs have many rows per user per day.

Write query() returning a SQLite SQL string. Tables: users(user_id INTEGER, signup_day TEXT) and activity(user_id INTEGER, day TEXT), dates as 'YYYY-MM-DD'. activity can have many rows per user per day, and some users have no activity at all.

Return one row per signup_day: (signup_day, cohort_size, d1_users, d7_users) where cohort_size counts users who signed up that day, d1_users counts those with activity on signup_day + 1 day, and d7_users those with activity on signup_day + 7 days. Order by signup_day ascending.

Signaturedef query()

Example

users 1 and 2 sign up on 2026-01-01; user 1 is active twice on 2026-01-02 and once on 2026-01-08; user 2 never comes back. Result: [('2026-01-01', 2, 1, 1)].

Understand the idea

Retention measures how many people from a group come back after a fixed time. A cohort is everyone who signed up on the same day. Day-N retention is the share of the cohort that was active exactly N days after signup.

Worked example: users 1 and 2 sign up on Jan 1. User 1 is active on Jan 2 (twice) and Jan 8. Day 1 is Jan 2, so d1_users = 1 (user 1 once, not twice). Day 7 is Jan 8, so d7_users = 1. Cohort size is 2, so both rates are 50 percent.

Rule: dN_users = COUNT(DISTINCT CASE WHEN activity_day = signup_day + N days THEN user_id END). Use a LEFT JOIN from users so inactive users stay in the denominator.

Chat apps, coding assistants and every subscription product track D1, D7 and D30 retention by cohort.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: example_run1(query())
  • Sample 2: two cohorts across a month end_run2(query())