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, and
  • event_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:

  1. plan_type — the exact tier value stored on the user record.
  2. users — total distinct user_ids in that tier, including accounts with zero qualifying events.
  3. retained_users — distinct user_ids in that tier with at least one event inside [signup_date, signup_date + 7 days).
  4. retention_rate — retained_users divided by users, 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_date values may be formatted as 'YYYY-MM-DD' (representing midnight 00:00:00), 'YYYY-MM-DD HH:MM:SS', or ISO 'YYYY-MM-DDTHH:MM:SS'.
  • users may contain duplicate rows for the same (user_id, signup_date, plan_type), and events may contain orphan user_ids absent from users (orphan events must not add rows or inflate counts).
  • plan_type values are case-sensitive ('Pro' and 'pro' are distinct groups) and may be NULL (forming its own NULL group).
  • Return retention_rate rounded to 4 decimal places; output row order is unrestricted.

Step-by-step walkthrough

  1. 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_type stored in users, 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_date and event_ts < signup_date + 7 days.
    • Inclusive denominator: Users with zero qualifying events still count in users, and plans with zero retained users still appear (with retained_users = 0 and retention_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_type as stored—do not merge 'Pro' with 'pro', and do not drop NULL plans.
  2. 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 at signup_date + 7 days minus 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_date with datetime(u.signup_date) for the start and datetime(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'. Leaving e.event_ts unwrapped also lets the database use an index on events(user_id, event_ts).

    (In native PostgreSQL with TIMESTAMP columns, the exact same condition is e.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)): if acct_2 signs up on Mar 11 at 14:30:00, an event on Mar 18 at 14:30:00 is 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')
    
  3. Preserve every user and plan with LEFT JOIN ... ON

    Because every user in users belongs in the denominator, we start FROM users AS u and LEFT JOIN events AS e. A LEFT JOIN keeps every row from the left table (users), filling the right table's columns (e.*) with NULL whenever no matching event exists.

    Crucially, the 7-day window condition must go inside ON, not WHERE:

    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_type
    
  4. Deduplicate users with COUNT(DISTINCT ...) and compute the rate

    When a user like acct_1 has two qualifying events in their first week, the LEFT JOIN produces two joined rows for acct_1 (this row multiplication is called fan-out). Using COUNT(*) would count acct_1 twice! Instead, inside each GROUP BY u.plan_type bucket:

    • COUNT(DISTINCT u.user_id) counts each unique user in the plan once, even if they triggered 50 events or appeared twice in users.
    • COUNT(DISTINCT e.user_id) counts each unique retained user once: e.user_id equals u.user_id when at least one first-week event matched, and is NULL otherwise (COUNT automatically ignores NULLs).
    • For retention_rate:
      • Multiply by 1.0 first so SQL performs floating-point division instead of integer division (1 / 2 would otherwise truncate to 0 in both SQLite and PostgreSQL).
      • Wrap the denominator in NULLIF(..., 0)—which returns NULL if its two arguments are equal—so a group of all-NULL user IDs cannot trigger a division-by-zero error.
      • Wrap the ratio in ROUND(..., 4) for four decimal places.
    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
    
  5. Trace 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                          | NULL
    

    Aggregating 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.0
    
  6. Complete SQL query

    Putting the SELECT, LEFT JOIN ... ON, and GROUP BY together 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 exactly 7 * 24 = 168 hours 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 with NULL.
  • 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 ignores NULLs and counts each unique value once, undoing event fan-out and duplicate user rows.
  • NULLIF(x, 0): A function that returns NULL when x = 0 (and x otherwise), turning potential division by zero into a clean NULL.

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-plan COUNT(DISTINCT ...) aggregates. Without an index, a hash join on user_id scans both tables in O(U + E) average time to pair matching user_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 for users and retained_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_date counts (>=), an event before signup_date does not (acct_4's pre-signup event), and an event at exact signup_date + 7 days does 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 events table): Kept with retained_users = 0 and retention_rate = 0.0 because LEFT JOIN preserves u.* rows and 0.0 / users = 0.0.
  • Orphan events for users missing from users: Ignored automatically because users is the left table of the LEFT 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 NULL plans: SQL GROUP BY keeps 'Pro', 'pro', and NULL as 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 users table: Produces zero groups and zero output rows.

Common mistakes

  • Putting the 7-day window filter in WHERE instead of ON: For non-retained users, e.event_ts is NULL, so WHERE e.event_ts >= ... evaluates to unknown and deletes those users—turning the LEFT JOIN into an INNER JOIN, inflating rates to 1.0, and erasing zero-retention plans.
  • Using COUNT(*) or COUNT(e.user_id) without DISTINCT: Counts joined event rows instead of unique people, allowing a single user with 5 events to exceed a 1.0 retention rate!
  • Using <= on the upper bound or comparing DATE(event_ts): Extends the window past 168 hours so acct_2's event at signup_date + 7 days wrongly counts.
  • Forgetting 1.0 * (integer division): In both SQLite and PostgreSQL, COUNT(...) / COUNT(...) divides two integers and truncates 1 / 2 to 0.
  • Comparing raw u.signup_date without datetime(...) in SQLite: If u.signup_date uses an ISO 'T' separator ('2025-08-10T10:00:00') while e.event_ts uses 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: Using LOWER(plan_type) or WHERE plan_type IS NOT NULL violates 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 users to matured signups whose 7-day window has completely elapsed—for instance, WHERE datetime(u.signup_date, '+7 days') <= :snapshot_ts (filtering u.* in WHERE happens on the left table and does not break the LEFT 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 at event_ts == signup_date matches every account and inflates retention to 100% across every tier. Exclude lifecycle/onboarding beacons inside the LEFT JOIN ... ON condition (such as AND 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 growth trial to eligible new accounts) to isolate causal lift.

Follow-up questions

Similar questions

More Mixpanel interview questions

All 7 Mixpanel questions →