KatInterview

Calculate Early User Retention Rates by Subscription Tier

SQL & DataModel answer
MediumModel answerSQL & Datasqlpostgresqlaggregations

Last updated

Compute 7-day retention rates across user subscription plans using PostgreSQL, handling distinct user counts, edge cases, and four-decimal precision.

You are analyzing user activity data to understand early engagement patterns across different subscription tiers.

You have access to two tables:

users

Column NameData TypeDescription
user_idintegerUnique identifier for the user
signup_datetimestampTimestamp when the user registered
plan_typestringSubscription plan chosen by the user

events

Column NameData TypeDescription
user_idintegerIdentifier of the user performing an action
event_tstimestampTimestamp when the activity occurred

A user is considered retained in their first week if they record at least one activity event within the 7-day window starting from their signup timestamp. Specifically, the event timestamp must satisfy: $$\text{signup_date} \le \text{event_ts} < \text{signup_date} + 7 \text{ days}$$

Write a single standard PostgreSQL query to evaluate first-week retention for every plan_type listed in the users table.

Your query should output the following columns in order:

  1. plan_type: The subscription plan name.
  2. users: Total number of distinct users registered under this plan type.
  3. retained_users: Total number of distinct users under this plan type who recorded at least one eligible event during their first 7 days.
  4. retention_rate: The proportion of retained users (retained_users / users), rounded to four decimal places.

Constraints & Requirements

  • All registered users within a plan tier must be included in the denominator (users), even if they recorded zero total events.
  • A user who triggers multiple events during their first 7 days must only be counted once toward retained_users.
  • Plans with zero retained users should still appear in the output, reporting retained_users = 0 and retention_rate = 0.0000.
  • Do not filter out, standardise, or alter any plan_type values (treat NULL or case variations strictly as distinct groups).
  • Output ordering is unconstrained.

Hints

Hint 1

Be careful with filtering after a LEFT JOIN: putting conditions on `events.event_ts` in a WHERE clause converts a LEFT JOIN into an INNER JOIN, excluding un-retained users.

Hint 2

Consider using an EXISTS subquery or counting distinct user IDs on a left-joined table to prevent multiple events from artificially inflating counts.

Hint 3

In PostgreSQL, `ROUND(val, 4)` requires a numeric data type. Cast your ratio or integer counts to `numeric` before rounding to avoid truncation from integer division.