Skip to main content

You have a users table with signup_date and an events table with user_id and event_date. Compute weekly retention by signup cohort: for each signup week, the share of users active in week 0, week 1, week 2 and so on. For example, if 3 users signed up in one week and 2 of them were active the following week, week 1 retention for that cohort is 67 percent.

Coding rounds · Intermediate 3

Short answer

Give each user a cohort week from signup_date. Join events to users and compute a week number: the whole weeks between the event week and the cohort week. Count distinct users per cohort and week number, then divide by the cohort size from the users table. The cost is one join and one GROUP BY over events.

Deeper answer

First clarify the definitions. Ask what counts as active: any event or a specific one. Ask whether weeks start on Monday, which timezone the dates use, and whether week 1 means days 7 to 13 after signup or the next calendar week.

Build it in CTEs. The first, cohort, gives each user a cohort week; in Postgres that is date_trunc('week', signup_date). The second, activity, joins events to cohort on user_id and computes week_number as the days between the event week and the cohort week, divided by 7. Select DISTINCT cohort_week, user_id, week_number there, so a user with ten events in a week counts once. The third, sizes, is COUNT(*) per cohort_week from cohort. The final query groups by cohort_week and week_number and returns 100.0 * COUNT(DISTINCT user_id) / cohort_size.

The denominator must come from the users table, not from events, or users who never came back are lost. Test a user with no events, a user with many events in one week, and the newest cohort, where later weeks have not happened yet and should be blank, not zero.

What a strong answer covers

Answer it out loud in the mock interview about 3 min

Follow-ups to expect

Common mistakes

Learn it

SQL for engineers

Practice Coding rounds questions

More on this topic

Today's AI turns are used

Lessons, roadmaps, videos, practice cards and the code playground stay free with your account, with no limit.