Calculate Early User Retention Rates by Subscription Tier
SQL & DataModel answerLast 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 Name | Data Type | Description |
|---|---|---|
user_id | integer | Unique identifier for the user |
signup_date | timestamp | Timestamp when the user registered |
plan_type | string | Subscription plan chosen by the user |
events
| Column Name | Data Type | Description |
|---|---|---|
user_id | integer | Identifier of the user performing an action |
event_ts | timestamp | Timestamp 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:
plan_type: The subscription plan name.users: Total number of distinct users registered under this plan type.retained_users: Total number of distinct users under this plan type who recorded at least one eligible event during their first 7 days.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 = 0andretention_rate = 0.0000. - Do not filter out, standardise, or alter any
plan_typevalues (treatNULLor 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.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach & Strategy
This problem requires computing a cohort retention rate grouped by category (plan_type). The primary technical challenges involve avoiding two common pitfalls:
- Filtering out un-retained users: If you perform a
LEFT JOINoneventsand place the timestamp condition in theWHEREclause, rows with no matching events (events.event_ts IS NULL) will be excluded. This turns the operation into anINNER JOIN, dropping non-retained users and artificially inflating the calculated retention rate. - Fan-out from multiple events: A user might log dozens of events during their first week. Joining
usersdirectly toeventswithout deduplicating will create multiple intermediate rows per user, which can skew aggregations if not handled with care.
Option 1: Correlated Subquery with EXISTS (Recommended)
Using EXISTS in a Common Table Expression (CTE) or subquery allows us to determine whether a user meets the retention criteria without expanding the number of rows. EXISTS short-circuits as soon as it finds a single qualifying event, which makes it both semantically safe and highly performant.
WITH user_retention AS (
SELECT
u.plan_type,
u.user_id,
EXISTS (
SELECT 1
FROM events e
WHERE e.user_id = u.user_id
AND e.event_ts >= u.signup_date
AND e.event_ts < u.signup_date + INTERVAL '7 days'
) AS is_retained
FROM users u
)
SELECT
plan_type,
COUNT(DISTINCT user_id) AS users,
COUNT(DISTINCT user_id) FILTER (WHERE is_retained) AS retained_users,
ROUND(
COUNT(DISTINCT user_id) FILTER (WHERE is_retained)::numeric
/ NULLIF(COUNT(DISTINCT user_id), 0),
4
) AS retention_rate
FROM user_retention
GROUP BY plan_type;
Option 2: LEFT JOIN with Predicate in ON Clause
Alternatively, you can left-join events to users, ensuring the timestamp range criteria is placed directly inside the ON clause:
SELECT
u.plan_type,
COUNT(DISTINCT u.user_id) AS users,
COUNT(DISTINCT e.user_id) AS retained_users,
ROUND(
COUNT(DISTINCT e.user_id)::numeric
/ NULLIF(COUNT(DISTINCT u.user_id), 0),
4
) AS retention_rate
FROM users u
LEFT JOIN events e
ON e.user_id = u.user_id
AND e.event_ts >= u.signup_date
AND e.event_ts < u.signup_date + INTERVAL '7 days'
GROUP BY u.plan_type;
Complexity Analysis
- Time Complexity:
- With an index on
events(user_id, event_ts), eachEXISTSprobe takes $O(\log E)$ time. For $U$ users, probing takes $O(U \log E)$. The grouping step takes $O(U \log U)$ or $O(U)$ depending on sort vs. hash aggregation. Total time: $\mathcal{O}(U \log E + U)$. - Without an index, Postgres typically performs a Hash Semi-Join, running in $\mathcal{O}(U + E)$ time.
- With an index on
- Space Complexity: $\mathcal{O}(U)$ space to store user retention status and aggregation states. The
EXISTSapproach avoids expanding intermediate memory, whereasLEFT JOINcan produce up to $\mathcal{O}(U \times E_{user})$ intermediate rows prior toGROUP BY.
Key Edge Cases & Considerations
| Edge Case | Handling |
|---|---|
| No events logged | Included in users total; is_retained resolves to FALSE. |
| Events logged before signup | Excluded via event_ts >= signup_date. |
| Event at exact boundary | event_ts = signup_date is retained; event_ts = signup_date + 7 days is excluded. |
| Multiple events per user | EXISTS evaluates once per user; COUNT(DISTINCT) prevents double counting. |
NULL plan types | PostgreSQL groups NULL values into a single group, satisfying requirement. |
| Division by Zero | NULLIF(COUNT(DISTINCT user_id), 0) prevents division-by-zero exceptions if a plan group has no valid user IDs. |