cswork / libraryOpen practice workspace

Coding questions · Mixpanel

Calculate First-Week Retention by Signup Cohort

Compute first-week activity retention by signup-week cohort with all cohort users in the denominator and zero-retention cohorts included.

Compute First-Week Retention by Signup Week

You have these tables:

TableColumnMeaning
usersuser_idUser identifier.
userssignup_dateThe user's signup date or timestamp.
usersplan_typeThe user's plan type.
eventsuser_idUser associated with an event.
eventsevent_tsEvent timestamp.

Group users into cohorts by the calendar week containing signup_date. In PostgreSQL, a calendar week begins on Monday at midnight. Name that week-start value signup_week.

For this exercise, a user is retained if the user has at least one matching event in the half-open interval from signup_date through, but not including, signup_date plus seven days. An event exactly at signup qualifies; an event exactly seven days later does not. Match events to users by user_id.

Write one read-only PostgreSQL query that returns one row for each signup-week cohort present in users, with these columns in this order:

  • signup_week: the cohort's week-start timestamp.
  • cohort_size: the number of distinct user identifiers in that cohort.
  • retained_users: the number of distinct users in that cohort meeting the first-week event condition.
  • retention_rate: retained_users divided by cohort_size, rounded to four decimal places.

The denominator includes cohort users with no qualifying event. Multiple qualifying events must not count a retained user more than once. Include cohorts with zero retained users; do not add calendar weeks that have no users.

Order the result by signup_week ascending. If a NULL week-start group is present, place it last.

Compute First-Week Retention by Signup Week

Table users

columntypeconstraints
user_idINTEGER
signup_dateTIMESTAMP
plan_typeTEXT

Sample data:

plan_typesignup_dateuser_id
free2026-09-06 23:30:001
pro2026-09-04 09:00:002
enterprise2026-08-31 12:00:003
free2026-09-07 00:00:004
pro2026-09-09 23:30:005
NULL2026-09-13 10:00:006
trial2026-09-21 09:00:007
free2026-09-23 12:00:008
pro2026-09-25 08:00:009
enterpriseNULL10
NULLNULL11

Table events

columntypeconstraints
user_idINTEGER
event_tsTIMESTAMP

Sample data:

event_tsuser_id
2026-09-06 23:30:001
2026-08-31 11:59:593
2026-09-07 12:00:003
2026-09-07 00:00:004
2026-09-07 00:00:004
2026-09-14 00:00:004
2026-09-16 23:29:595
2026-09-10 12:00:005
2026-09-28 09:00:007
2026-09-23 11:59:598
NULL9
2026-09-10 12:00:0010
2026-09-10 12:00:0099
2026-09-10 12:00:00NULL

Expected output

signup_weekcohort_sizeretained_usersretention_rate
2026-08-31 00:00:00310.3333
2026-09-07 00:00:00320.6667
2026-09-21 00:00:00300
NULL200