Seven-Day User Retention Across Subscription Tiers
Medium · Data Manipulation (SQL/Python) · Data Scientist · Technical Screen
Problem Statement
Product analytics tracks newly registered accounts alongside a log of timestamped product interactions. Each account in users has a registration timestamp (signup_date) and a recorded subscription tier (plan_type), while events logs activity timestamps (event_ts) keyed by user_id.
An account counts as first-week retained when events contains one or more rows for that user_id satisfying the half-open 7-day window:
event_ts >= signup_date, andevent_ts < signup_date + 7 days(strictly before 168 hours after registration).
Write a single read-only SQL query (QUERY in SQLite dialect) that computes first-week retention for every recorded plan_type present in users, returning four columns in exact order:
plan_type— the exact tier value stored on the user record.users— total distinctuser_ids in that tier, including accounts with zero qualifying events.retained_users— distinctuser_ids in that tier with at least one event inside[signup_date, signup_date + 7 days).retention_rate—retained_usersdivided byusers, rounded to 4 decimal places.
Keep tiers whose retained_users count is 0, count each qualifying account at most once even if it generated multiple first-week events, and group strictly by the raw plan_type value without case-folding, merging, or dropping NULL tiers. Output rows may appear in any order.
Input Schema
users
| Column | Type | Description |
|---|---|---|
user_id |
VARCHAR |
Account identifier linking to events.user_id. |
signup_date |
TIMESTAMP |
Account creation date or timestamp (YYYY-MM-DD or ISO timestamp). |
plan_type |
VARCHAR |
Recorded subscription tier (may vary in case or be NULL). |
events
| Column | Type | Description |
|---|---|---|
user_id |
VARCHAR |
Account identifier that triggered the interaction. |
event_ts |
TIMESTAMP |
Timestamp when the interaction occurred. |
Examples
Example 1
Input:
users
user_id |
signup_date |
plan_type |
|---|---|---|
'acct_1' |
'2025-03-10 08:00:00' |
'starter' |
'acct_2' |
'2025-03-11 14:30:00' |
'starter' |
'acct_3' |
'2025-03-12 09:00:00' |
'starter' |
'acct_4' |
'2025-03-14 00:00:00' |
'growth' |
'acct_5' |
'2025-03-15 18:00:00' |
'growth' |
'acct_6' |
'2025-03-16 12:00:00' |
'scale' |
events
user_id |
event_ts |
|---|---|
'acct_1' |
'2025-03-10 08:00:00' |
'acct_1' |
'2025-03-13 19:15:00' |
'acct_2' |
'2025-03-18 14:30:00' |
'acct_3' |
'2025-03-19 08:59:59' |
'acct_4' |
'2025-03-13 23:50:00' |
'acct_4' |
'2025-03-16 11:00:00' |
'acct_5' |
'2025-03-28 10:00:00' |
Expected Output:
plan_type |
users |
retained_users |
retention_rate |
|---|---|---|---|
'starter' |
3 |
2 |
0.6667 |
'growth' |
2 |
1 |
0.5 |
'scale' |
1 |
0 |
0.0 |
Explanation:
- In 'starter', acct_1 qualifies (counted once despite two week-1 events) and acct_3 qualifies (2025-03-19 08:59:59 is 1 second before the 7-day cutoff), whereas acct_2's event at '2025-03-18 14:30:00' lands on the exclusive upper boundary (signup_date + 7 days), giving 2 / 3 = 0.6667.
- In 'growth', acct_4's pre-signup event (2025-03-13 23:50:00) is ignored while its 2025-03-16 event qualifies; acct_5's only event occurs after 7 days, giving 1 / 2 = 0.5.
- In 'scale', acct_6 has no events, so the tier remains in the output with 0 retained users and rate 0.0.
Constraints
signup_datevalues may be formatted as'YYYY-MM-DD'(representing midnight00:00:00),'YYYY-MM-DD HH:MM:SS', or ISO'YYYY-MM-DDTHH:MM:SS'.usersmay contain duplicate rows for the same(user_id, signup_date, plan_type), andeventsmay contain orphanuser_ids absent fromusers(orphan events must not add rows or inflate counts).plan_typevalues are case-sensitive ('Pro'and'pro'are distinct groups) and may beNULL(forming its ownNULLgroup).- Return
retention_raterounded to 4 decimal places; output row order is unrestricted.
Step-by-step walkthrough
Understand the retention definition and output contract
We have two tables:
users(user_id, signup_date, plan_type): each user's signup date/timestamp and recorded plan group.events(user_id, event_ts): timestamped activity events for users.
We want one output row per distinct
plan_typestored inusers, with four columns in exact order:plan_type, users, retained_users, retention_rate.Every rule in the specification matters:
- First-week window: A user is retained if they have at least one event where
event_ts >= signup_dateandevent_ts < signup_date + 7 days. - Inclusive denominator: Users with zero qualifying events still count in
users, and plans with zero retained users still appear (withretained_users = 0andretention_rate = 0.0). - Distinct user counts: Multiple qualifying events for the same user (or duplicate rows in
users) still count that user only once. - Exact recorded plan values: Group by
plan_typeas stored—do not merge'Pro'with'pro', and do not dropNULLplans.
Model the 7-day half-open window accurately
The retention window
[signup_date, signup_date + 7 days)is a half-open interval—an interval that includes its start endpoint ([) and excludes its end endpoint ()):signup_date signup_date + 7 days | | excluded [================== INCLUDED ===================) excluded ... 11:59:59 12:00:00 11:59:59 12:00:00 ...- Start (
>=): An event at the exact second of signup counts, while an event 1 second before signup is excluded. - End (
<): An event atsignup_date + 7 daysminus 1 second counts, while an event exactly 7 days (168 hours) after signup is outside the first week.
Because our test runner executes SQLite—which stores timestamps as text—we normalize
u.signup_datewithdatetime(u.signup_date)for the start anddatetime(u.signup_date, '+7 days')for the end. Both produce canonical'YYYY-MM-DD HH:MM:SS'strings, so a date-only signup like'2025-08-10'cleanly becomes'2025-08-10 00:00:00'and an ISO'T'signup like'2025-08-10T10:00:00'becomes'2025-08-10 10:00:00'. Leavinge.event_tsunwrapped also lets the database use an index onevents(user_id, event_ts).(In native PostgreSQL with
TIMESTAMPcolumns, the exact same condition ise.event_ts >= u.signup_date AND e.event_ts < u.signup_date + INTERVAL '7 days'.)Never strip times down to calendar dates (
date(e.event_ts)): ifacct_2signs up on Mar 11 at14:30:00, an event on Mar 18 at14:30:00is 168 hours later and must not count.ON e.user_id = u.user_id AND e.event_ts >= datetime(u.signup_date) AND e.event_ts < datetime(u.signup_date, '+7 days')- Start (
Preserve every user and plan with LEFT JOIN ... ON
Because every user in
usersbelongs in the denominator, we startFROM users AS uandLEFT JOIN events AS e. ALEFT JOINkeeps every row from the left table (users), filling the right table's columns (e.*) withNULLwhenever no matching event exists.Crucially, the 7-day window condition must go inside
ON, notWHERE:What happens to acct_6 ('scale', no events) and acct_5 ('growth', event on day 13)? With window in ON (CORRECT): u.user_id | u.plan_type | e.user_id | e.event_ts ----------+-------------+-----------+----------- acct_5 | growth | NULL | NULL <-- kept in denominator! acct_6 | scale | NULL | NULL <-- keeps 'scale' tier alive! With window in WHERE (BROKEN): WHERE runs AFTER the join -> sees e.event_ts IS NULL -> deletes both acct_5 and acct_6! 'growth' jumps from 1/2 (0.5) to 1/1 (1.0), and 'scale' vanishes completely!FROM users AS u -- LEFT JOIN keeps non-retained users in the denominator; the 7-day window must sit in ON, not WHERE LEFT JOIN events AS e ON e.user_id = u.user_id AND e.event_ts >= datetime(u.signup_date) AND e.event_ts < datetime(u.signup_date, '+7 days') GROUP BY u.plan_typeDeduplicate users with COUNT(DISTINCT ...) and compute the rate
When a user like
acct_1has two qualifying events in their first week, theLEFT JOINproduces two joined rows foracct_1(this row multiplication is called fan-out). UsingCOUNT(*)would countacct_1twice! Instead, inside eachGROUP BY u.plan_typebucket:COUNT(DISTINCT u.user_id)counts each unique user in the plan once, even if they triggered 50 events or appeared twice inusers.COUNT(DISTINCT e.user_id)counts each unique retained user once:e.user_idequalsu.user_idwhen at least one first-week event matched, and isNULLotherwise (COUNTautomatically ignoresNULLs).- For
retention_rate:- Multiply by
1.0first so SQL performs floating-point division instead of integer division (1 / 2would otherwise truncate to0in both SQLite and PostgreSQL). - Wrap the denominator in
NULLIF(..., 0)—which returnsNULLif its two arguments are equal—so a group of all-NULLuser IDs cannot trigger a division-by-zero error. - Wrap the ratio in
ROUND(..., 4)for four decimal places.
- Multiply by
SELECT u.plan_type, -- Count distinct user IDs so multiple qualifying events (or duplicate user rows) count once COUNT(DISTINCT u.user_id) AS users, COUNT(DISTINCT e.user_id) AS retained_users, -- Multiply by 1.0 to avoid integer division; NULLIF prevents division by zero ROUND( 1.0 * COUNT(DISTINCT e.user_id) / NULLIF(COUNT(DISTINCT u.user_id), 0), 4 ) AS retention_rateTrace Example 1 step by step
Let's check every user's 7-day window against
events:user | plan | window [signup, signup + 7d) | events in window | e.user_id -------+---------+---------------------------------------+-------------------------------+------------- acct_1 | starter | [2025-03-10 08:00, 2025-03-17 08:00) | 03-10 08:00, 03-13 19:15 | 'acct_1' (x2) acct_2 | starter | [2025-03-11 14:30, 2025-03-18 14:30) | none (03-18 14:30 is ==) | NULL acct_3 | starter | [2025-03-12 09:00, 2025-03-19 09:00) | 03-19 08:59:59 | 'acct_3' acct_4 | growth | [2025-03-14 00:00, 2025-03-21 00:00) | 03-16 11:00 (03-13 23:50 < ) | 'acct_4' acct_5 | growth | [2025-03-15 18:00, 2025-03-22 18:00) | none (03-28 is too late) | NULL acct_6 | scale | [2025-03-16 12:00, 2025-03-23 12:00) | none | NULLAggregating by
plan_type:plan_type | DISTINCT u.user_id | DISTINCT e.user_id | retention_rate ----------+-----------------------------+----------------------+------------------------- starter | {acct_1, acct_2, acct_3}->3 | {acct_1, acct_3}->2 | ROUND(2.0 / 3, 4) = 0.6667 growth | {acct_4, acct_5} ->2 | {acct_4} ->1 | ROUND(1.0 / 2, 4) = 0.5 scale | {acct_6} ->1 | {} ->0 | ROUND(0.0 / 1, 4) = 0.0Complete SQL query
Putting the
SELECT,LEFT JOIN ... ON, andGROUP BYtogether gives the final query:SELECT u.plan_type, -- Count distinct user IDs so multiple qualifying events (or duplicate user rows) count once COUNT(DISTINCT u.user_id) AS users, COUNT(DISTINCT e.user_id) AS retained_users, -- Multiply by 1.0 to avoid integer division; NULLIF prevents division by zero ROUND( 1.0 * COUNT(DISTINCT e.user_id) / NULLIF(COUNT(DISTINCT u.user_id), 0), 4 ) AS retention_rate FROM users AS u -- LEFT JOIN keeps non-retained users in the denominator; the 7-day window must sit in ON, not WHERE LEFT JOIN events AS e ON e.user_id = u.user_id AND e.event_ts >= datetime(u.signup_date) AND e.event_ts < datetime(u.signup_date, '+7 days') GROUP BY u.plan_type✅ Submit now — all tests should pass.
Intuition & how it works
Imagine taking first-week attendance for new members at a gym across subscription tiers (starter, growth, scale). You start with the complete signup roster on your clipboard so nobody disappears from the headcount. Next to each member's name, you attach any check-ins that occurred during their personal 168-hour window ([signup_date, signup_date + 7 days)), leaving the check-in column blank (NULL) if they never showed up during that week. Finally, for each tier, you count how many unique members have at least one attached check-in and divide by how many unique members are on the roster.
Why does the naive query go wrong? Using an INNER JOIN—or using a LEFT JOIN and accidentally placing the 7-day timestamp check in WHERE—discards every user who had no qualifying event, inflating retention rates toward 1.0 and completely deleting tiers with zero retained users like scale. Counting rows with COUNT(*) instead of COUNT(DISTINCT ...) counts an active user with multiple first-week events as multiple separate people, and comparing calendar dates (date(event_ts)) instead of timestamps wrongly includes events past the 168-hour cutoff.
Walk through four users from Example 1—acct_1 (starter, Mar 10 08:00, events Mar 10 08:00 and Mar 13), acct_2 (starter, Mar 11 14:30, event Mar 18 14:30), acct_3 (starter, Mar 12 09:00, event Mar 19 08:59:59), and acct_6 (scale, Mar 16, no events):
1. LEFT JOIN events ON user_id and [signup_date, signup_date + 7 days):
acct_1 (starter) -> matches 2 events -> 2 rows with e.user_id = 'acct_1'
acct_2 (starter) -> Mar 18 14:30 is == signup + 7d (strictly < fails) -> 1 row with e.user_id = NULL
acct_3 (starter) -> Mar 19 08:59:59 is 1s before cutoff -> 1 row with e.user_id = 'acct_3'
acct_6 (scale) -> no events -> 1 row with e.user_id = NULL
2. GROUP BY plan_type with COUNT(DISTINCT u.user_id) and COUNT(DISTINCT e.user_id):
starter: users = |{acct_1, acct_2, acct_3}| = 3, retained = |{acct_1, acct_3}| = 2 -> ROUND(2.0/3, 4) = 0.6667
scale: users = |{acct_6}| = 1, retained = |{}| = 0 -> ROUND(0.0/1, 4) = 0.0
Key concepts used here:
- Half-open interval
[a, b): A range that includes the start boundary (>= a) and excludes the end boundary (< b), ensuring a 7-day window spans exactly7 * 24 = 168hours rather than 7 days plus 1 extra second. LEFT JOIN: A join that keeps every row from the left table (users) even when no matching row exists in the right table (events), filling unmatched right-side columns withNULL.- Fan-out: When one left-table row matches multiple right-table rows, multiplying the row count in the intermediate join result.
COUNT(DISTINCT col): An aggregate that ignoresNULLs and counts each unique value once, undoing event fan-out and duplicate user rows.NULLIF(x, 0): A function that returnsNULLwhenx = 0(andxotherwise), turning potential division by zero into a cleanNULL.
Complexity
Let U be the number of rows in users, E be the number of rows in events, and J be the number of joined rows produced (U <= J <= U + U * E, and typically J <= U + E when user_id is unique in users).
- Time: With a composite B-tree index on
events(user_id, event_ts), each of the U users performs one index seek and scans only its qualifying first-week events, running in O(U log E + J) time, followed by O(J) average time (or O(J log J) with sorting) to compute the per-planCOUNT(DISTINCT ...)aggregates. Without an index, a hash join onuser_idscans both tables in O(U + E) average time to pair matchinguser_ids and evaluates the window check on each candidate pair. - Space: O(U) memory across all plan groups to track the sets of distinct
user_ids forusersandretained_users(plus O(min(U, E)) memory if the database builds an in-memory hash table for an unindexed join).
Indexes: A composite index on events(user_id, event_ts) is ideal because e.user_id = u.user_id is an equality match on the leading column and e.event_ts >= ... AND e.event_ts < ... is a sargable range scan (a condition written on a bare column without wrapping e.event_ts in a function, so the engine can jump directly into the B-tree range). Notice that we applied datetime(...) only to u.signup_date, keeping e.event_ts bare and index-friendly.
Edge cases
- Exact window boundaries: An event at
event_ts == signup_datecounts (>=), an event beforesignup_datedoes not (acct_4's pre-signup event), and an event at exactsignup_date + 7 daysdoes not (<,acct_2's event). - Multiple first-week events for one user:
COUNT(DISTINCT e.user_id)counts that user once rather than once per event. - Plans with zero retained users (or empty
eventstable): Kept withretained_users = 0andretention_rate = 0.0becauseLEFT JOINpreservesu.*rows and0.0 / users = 0.0. - Orphan events for users missing from
users: Ignored automatically becauseusersis the left table of theLEFT JOIN. - Duplicate rows for the same user in
users:COUNT(DISTINCT u.user_id)deduplicates the denominator as well as the numerator. - Case sensitivity and
NULLplans: SQLGROUP BYkeeps'Pro','pro', andNULLas three separate plan groups without collapsing or dropping them. - Date-only or ISO
'T'signups in SQLite:datetime(u.signup_date)normalizes both'2025-08-10'(to'2025-08-10 00:00:00') and'2025-08-10T10:00:00'(to'2025-08-10 10:00:00') so text comparisons match exact chronological order. - Empty
userstable: Produces zero groups and zero output rows.
Common mistakes
- Putting the 7-day window filter in
WHEREinstead ofON: For non-retained users,e.event_tsisNULL, soWHERE e.event_ts >= ...evaluates to unknown and deletes those users—turning theLEFT JOINinto anINNER JOIN, inflating rates to1.0, and erasing zero-retention plans. - Using
COUNT(*)orCOUNT(e.user_id)withoutDISTINCT: Counts joined event rows instead of unique people, allowing a single user with 5 events to exceed a1.0retention rate! - Using
<=on the upper bound or comparingDATE(event_ts): Extends the window past 168 hours soacct_2's event atsignup_date + 7 dayswrongly counts. - Forgetting
1.0 *(integer division): In both SQLite and PostgreSQL,COUNT(...) / COUNT(...)divides two integers and truncates1 / 2to0. - Comparing raw
u.signup_datewithoutdatetime(...)in SQLite: Ifu.signup_dateuses an ISO'T'separator ('2025-08-10T10:00:00') whilee.event_tsuses a space ('2025-08-10 12:00:00'), raw ASCII comparison says' ' < 'T'and falsely rejects same-day post-signup events. - Lowercasing or filtering
plan_type: UsingLOWER(plan_type)orWHERE plan_type IS NOT NULLviolates the requirement to report every recorded plan value as stored.
Alternative approaches
Instead of joining all qualifying events and deduplicating after fan-out, you can check each user with a correlated EXISTS subquery—which stops scanning a user's events as soon as the first qualifying event is found! When users has unique user_ids, this completely avoids row fan-out (DISTINCT is kept below only in case users itself has duplicate rows):
WITH user_flags AS (
SELECT
u.user_id,
u.plan_type,
CASE
WHEN EXISTS (
SELECT 1
FROM events AS e
WHERE e.user_id = u.user_id
AND e.event_ts >= datetime(u.signup_date)
AND e.event_ts < datetime(u.signup_date, '+7 days')
) THEN u.user_id
END AS retained_user_id
FROM users AS u
)
SELECT
plan_type,
COUNT(DISTINCT user_id) AS users,
COUNT(DISTINCT retained_user_id) AS retained_users,
ROUND(
1.0 * COUNT(DISTINCT retained_user_id) / NULLIF(COUNT(DISTINCT user_id), 0),
4
) AS retention_rate
FROM user_flags
GROUP BY plan_type
With an index on events(user_id, event_ts), EXISTS is especially fast for heavy power users who generate thousands of events in week 1, because it reads only 1 index entry per user instead of thousands.
Follow-up questions
-
Why does running this query on today's live table underestimate recent signups, and how should you restrict the cohort? Accounts created fewer than 7 days ago have not completed their full 168-hour observation window yet (right-censoring), so users who will return on day 5 or day 6 currently look unretained and pull the rate downward. Restrict
usersto matured signups whose 7-day window has completely elapsed—for instance,WHERE datetime(u.signup_date, '+7 days') <= :snapshot_ts(filteringu.*inWHEREhappens on the left table and does not break theLEFT JOIN). -
How does your metric break if the tracking pipeline automatically emits a signup event at signup_date, and how would you adjust the query? Because the lower endpoint is inclusive (
>=), a system-generated'signup_completed'event atevent_ts == signup_datematches every account and inflates retention to100%across every tier. Exclude lifecycle/onboarding beacons inside theLEFT JOIN ... ONcondition (such asAND e.event_name NOT IN ('signup_completed', 'account_created')), or redefine retention over[signup_date + 1 day, signup_date + 7 days)when measuring post-signup return visits. -
If the growth tier shows higher first-week retention than starter, can you conclude that upgrading users causes better retention? Not from observational logs alone, because selection bias—systematic pre-signup differences between people who voluntarily choose paid vs entry-level tiers—confounds the comparison (paid signups typically arrive with higher urgency or team sponsorship). Quantify sampling uncertainty first (with a two-proportion z-test—a hypothesis test checking whether two observed proportions differ beyond random noise—or Fisher's exact test on small cohorts), and run a randomized experiment (such as granting a randomized
growthtrial to eligible new accounts) to isolate causal lift.
Follow-up questions
- Why does running this query on today's live table underestimate recent signups, and how should you restrict the cohort?
- How does your metric break if the tracking pipeline automatically emits a signup event at signup_date, and how would you adjust the query?
- If the growth tier shows higher first-week retention than starter, can you conclude that upgrading users causes better retention?
Similar questions
- Seven-Day Retention Rates by Weekly Cohort
- Distinct Users with Post-Signup Activity
- Day-Seven Calendar Retention Count
- Hierarchical Event Counts by Attribute Order
- Exact Sum of Decimal Strings
- Evaluating Predictive Signals for Customer Retention