Daily User Growth and Churn Rollup

Medium · Data Manipulation (SQL/Python) · Data Scientist · Technical Screen

Problem Statement

Given an application telemetry table events, write a single SQLite query assigned to QUERY that computes daily user acquisition, retention, churn, and net user counts for a parameterized target UTC date :today ('YYYY-MM-DD'), both across all platforms combined and broken down by device_platform.

Table Schema

events: - device_id (TEXT): unique identifier of the client device (may be NULL for unauthenticated logs). - event_name (TEXT): action name such as 'play', 'pause', 'browse', or 'search'. - ts (TIMESTAMP): ISO-8601 UTC timestamp string (for example, '2026-04-15T09:15:00Z'). - device_platform (TEXT): client surface such as 'android', 'ios', 'tv', or 'web' (may be NULL).

Metric & Attribution Rules

Let today = DATE(:today) and yesterday = DATE(:today, '-1 day'), where each row's calendar day is DATE(ts) in UTC:

  • Filtering & deduplication: Ignore any row where device_id IS NULL. Multiple events from the same device_id on the same UTC date count that device once.
  • Bucket definitions (for :today):
    • new_users: distinct devices active on today whose earliest UTC DATE(ts) across the entire events table equals today.
    • retained_users: distinct devices active on both yesterday and today.
    • churn_users: distinct devices active on yesterday and not active on today.
    • net_users: new_users + retained_users - churn_users.
    • (Note: a returning dormant device—seen strictly before yesterday, inactive on yesterday, and active on today—belongs to none of the three buckets.)
  • Single-platform attribution: Every device active in (yesterday, today) is assigned a single platform equal to COALESCE(device_platform, 'unknown') from its latest event (MAX(ts)) within (yesterday, today). If multiple events share that exact MAX(ts), break ties by choosing the alphabetically smallest platform name (MIN).
  • Output columns & ordering: Return (event_date, device_platform, new_users, retained_users, churn_users, net_users) with event_date = today. Output the overall summary row (device_platform = 'ALL') first—returning 0 for each count when no devices qualify—followed in ascending alphabetical order by one row per device_platform that has at least one new, retained, or churned device.

Examples

Example 1

Parameter :today = '2026-04-15' (yesterday = '2026-04-14').

events:
+-----------+------------+----------------------+-----------------+
| device_id | event_name | ts                   | device_platform |
+-----------+------------+----------------------+-----------------+
| d10       | play       | 2026-04-14T23:45:00Z | ios             |
| d10       | pause      | 2026-04-15T00:20:00Z | ios             |
| d20       | browse     | 2026-04-15T09:15:00Z | android         |
| d30       | play       | 2026-04-15T14:00:00Z | ios             |
| d40       | browse     | 2026-04-15T18:30:00Z | web             |
| d50       | play       | 2026-04-13T11:00:00Z | android         |
| d50       | play       | 2026-04-14T19:00:00Z | android         |
| d60       | search     | 2026-04-14T16:10:00Z | web             |
| d60       | play       | 2026-04-16T02:00:00Z | web             |
+-----------+------------+----------------------+-----------------+

Expected output:
+------------+-----------------+-----------+----------------+-------------+-----------+
| event_date | device_platform | new_users | retained_users | churn_users | net_users |
+------------+-----------------+-----------+----------------+-------------+-----------+
| 2026-04-15 | ALL             | 3         | 1              | 2           | 2         |
| 2026-04-15 | android         | 1         | 0              | 1           | 0         |
| 2026-04-15 | ios             | 1         | 1              | 0           | 2         |
| 2026-04-15 | web             | 1         | 0              | 1           | 0         |
+------------+-----------------+-----------+----------------+-------------+-----------+

Walk-through: d10 has events on both 2026-04-14 and 2026-04-15 across UTC midnight (retained on ios). d20 (android), d30 (ios), and d40 (web) appear for the first time on 2026-04-15 (new). d50 (android) and d60 (web, whose next event on 2026-04-16 is after :today) were active on 2026-04-14 and absent on 2026-04-15 (churn). Summing gives new = 3, retained = 1, churn = 2, and net = 3 + 1 - 2 = 2.

Example 2

Parameter :today = '2026-04-15' (yesterday = '2026-04-14').

events:
+-----------+------------+----------------------+-----------------+
| device_id | event_name | ts                   | device_platform |
+-----------+------------+----------------------+-----------------+
| d70       | browse     | 2026-04-10T08:00:00Z | web             |
| d70       | browse     | 2026-04-15T08:00:00Z | web             |
| d80       | play       | 2026-04-14T10:00:00Z | ios             |
| d80       | play       | 2026-04-15T11:00:00Z | tv              |
| d90       | browse     | 2026-04-15T15:00:00Z | tv              |
| d90       | search     | 2026-04-15T15:00:00Z | android         |
| d95       | play       | 2026-04-14T20:00:00Z | NULL            |
| NULL      | play       | 2026-04-15T12:00:00Z | ios             |
+-----------+------------+----------------------+-----------------+

Expected output:
+------------+-----------------+-----------+----------------+-------------+-----------+
| event_date | device_platform | new_users | retained_users | churn_users | net_users |
+------------+-----------------+-----------+----------------+-------------+-----------+
| 2026-04-15 | ALL             | 1         | 1              | 1           | 1         |
| 2026-04-15 | android         | 1         | 0              | 0           | 1         |
| 2026-04-15 | tv              | 0         | 1              | 0           | 1         |
| 2026-04-15 | unknown         | 0         | 0              | 1           | -1        |
+------------+-----------------+-----------+----------------+-------------+-----------+

Walk-through: d70 is a returning dormant device (first seen 2026-04-10, inactive 2026-04-14, active 2026-04-15), so it enters no bucket and web is omitted. d80 is retained and credited to its latest platform tv. d90 is new with two tied timestamps at 15:00:00Z, breaking alphabetically to android. d95 churns with NULL platform mapped to 'unknown', and the NULL device_id row is ignored.

Constraints

  • Write a single SQL query in QUERY (SQLite dialect using CTEs; window functions are not required) taking :today as its named parameter.
  • events may contain 0 rows, duplicate rows, NULL values in device_id or device_platform, and timestamps before or after :today.
  • Calendar date arithmetic must handle month-end and leap-year boundaries accurately (for example, :today = '2024-03-01' has yesterday = '2024-02-29').

Step-by-step walkthrough

  1. Understand the four metrics and pin down edge-case rules

    We are given a raw events(device_id, event_name, ts, device_platform) table and one target UTC date (:today, such as '2026-04-15'). Comparing :today against the day right before it (yesterday, '2026-04-14'), each device falls into at most one of three counted buckets:

    device activity history (UTC dates)                 bucket on :today
    --------------------------------------------------  ----------------
    ... [never seen] | [no 04-14] | [ACTIVE 04-15]      new
    ... [any]        | [ACTIVE 04-14] | [ACTIVE 04-15]  retained
    ... [any]        | [ACTIVE 04-14] | [no 04-15]      churn
    ... [seen <= 04-13] | [no 04-14] | [ACTIVE 04-15]   resurrected (in NONE of the 3 buckets)
    
    net_users = new_users + retained_users - churn_users
    

    Notice a subtle trap in the formula: net_users is not DAU(today) - DAU(yesterday). Why? Today's daily active users (DAU) equal new + retained + resurrected, whereas yesterday's equal retained + churn. Their difference is new + resurrected - churn, which leaves out retained and includes resurrected. Always implement the exact formula asked (new + retained - churn), while mentioning that distinction in an interview.

    Before writing any SQL, state clear rules for the messy cases real logs always contain:

    Open question Rule we use Why this choice makes sense
    User switches platform between yesterday and today Assign the platform of the device's latest event in (yesterday, today) Each device gets one platform, so per-platform counts add up cleanly to the 'ALL' row
    Tie at the exact same latest timestamp Pick the alphabetically first platform (MIN(device_platform)) Makes the output 100% deterministic without needing window functions
    device_platform is NULL Replace with 'unknown' Keeps the device in both the 'ALL' total and a visible 'unknown' breakdown row
    device_id is NULL Ignore the row Anonymous rows cannot be linked across days for retention or churn
    Duplicate or multiple events on the same day Deduplicate per (device_id, day) Opening the app 10 times in one day is still 1 active user
    Overall summary row and empty logs Emit device_platform = 'ALL' first, with 0s if no devices qualify Gives dashboards one consistent table even on an empty day
  2. Trace Example 1 by hand

    Before touching SQL, classify each of the six Example 1 devices for :today = '2026-04-15' (yesterday = '2026-04-14'):

    device  first-ever UTC day  active 04-14?     active 04-15?     bucket    latest platform (04-14..04-15)
    ------  ------------------  ----------------  ----------------  --------  ------------------------------
    d10     2026-04-14          yes (23:45:00Z)   yes (00:20:00Z)   retained  ios
    d20     2026-04-15          no                yes (09:15:00Z)   new       android
    d30     2026-04-15          no                yes (14:00:00Z)   new       ios
    d40     2026-04-15          no                yes (18:30:00Z)   new       web
    d50     2026-04-13          yes (19:00:00Z)   no                churn     android
    d60     2026-04-14          yes (16:10:00Z)   no  (04-16 only)  churn     web
    

    Two rows are especially instructive: - d10 has two events only 35 minutes apart (2026-04-14T23:45:00Z and 2026-04-15T00:20:00Z). Because they cross UTC midnight, d10 is active on both UTC days and counts as retained. In US Pacific time (UTC-7), both timestamps would land on 2026-04-14 and d10 would become churned. - d60 comes back on 2026-04-16, which is after :today. Relative to 2026-04-15, d60 was active yesterday and missing today, so it is churned.

    Rolling up those six devices gives our expected target output:

    event_date  device_platform  new_users  retained_users  churn_users  net_users
    ----------  ---------------  ---------  --------------  -----------  ---------
    2026-04-15  ALL              3          1               2            2
    2026-04-15  android          1          0               1            0
    2026-04-15  ios              1          1               0            2
    2026-04-15  web              1          0               1            0
    

    Check the arithmetic: across the three platforms, new = 1 + 1 + 1 = 3, retained = 0 + 1 + 0 = 1, churn = 1 + 0 + 1 = 2, and net = 0 + 2 + 0 = 2. Every column adds up to 'ALL'.

  3. Plan the query as a pipeline of small CTEs

    Trying to compute first-ever date, active yesterday, active today, and latest platform inside one giant SELECT ... GROUP BY quickly tangles row-level events with user-level cohorts. Instead, we use CTEs (Common Table Expressions — named WITH subqueries that act like clean step-by-step temporary tables) so each block does one tiny job:

    events (all history)
      |-- first_seen       : [device_id, first_date] over ALL dates
      |-- window_events    : [device_id, event_date, ts, device_platform] on yesterday & today only
            |-- yesterday_active : [device_id] distinct yesterday
            |-- today_active     : [device_id] distinct today
            |-- last_event       : [device_id, last_ts] latest timestamp in window
                  |-- device_label : [device_id, device_platform] 1 platform per device
    
    first_seen + yesterday_active + today_active
      |-- new_devices, retained_devices, churned_devices  (3 non-overlapping device sets)
            |-- flags + labeled  : [device_platform, is_new, is_retained, is_churn]
                  |-- totals     : 'ALL' row UNION ALL per-platform rows
    

    Working with sets of distinct device_ids guarantees that duplicate events or power users with 500 clicks never inflate user counts.

  4. Step 1 in SQL: compute date bounds, first-ever day, and the two-day window

    First, bounds computes today and yesterday from :today using SQLite's DATE(:today, '-1 day') (in ANSI/Postgres/BigQuery SQL, write CAST(:today AS DATE) - INTERVAL '1' DAY). Using calendar arithmetic instead of string slicing handles month rollovers and leap years like 2024-03-01 -> 2024-02-29.

    Next, first_seen must scan the entire events table, not just the two-day window. If you filtered events to 04-14 and 04-15 first, a user who visited on 04-10, skipped 04-14, and returned on 04-15 (like d70 in Example 2) would falsely look like a brand-new user. Only window_events restricts rows to yesterday and today.

    WITH bounds AS (
        -- Compute today and yesterday in UTC calendar dates (handles month and leap-year rollovers)
        SELECT DATE(:today) AS today, DATE(:today, '-1 day') AS yesterday
    ),
    first_seen AS (
        -- Scan full event history to find the first UTC date each device ever appeared
        SELECT device_id, MIN(DATE(ts)) AS first_date
        FROM events
        WHERE device_id IS NOT NULL
        GROUP BY device_id
    ),
    window_events AS (
        -- Keep only yesterday's and today's valid events and normalize NULL platform to 'unknown'
        SELECT
            e.device_id,
            DATE(e.ts) AS event_date,
            e.ts,
            COALESCE(e.device_platform, 'unknown') AS device_platform
        FROM events AS e
        CROSS JOIN bounds AS b
        WHERE e.device_id IS NOT NULL
          AND DATE(e.ts) IN (b.yesterday, b.today)
    ),
    
  5. Step 2 in SQL: deduplicate active devices and pick one platform per device

    From window_events, SELECT DISTINCT device_id gives us the exact set of devices active yesterday and the set active today.

    To pick one platform per device without window functions (ROW_NUMBER()), we use a classic two-step aggregation: 1. last_event finds each device's latest timestamp MAX(ts) inside the two-day window. 2. device_label joins back to window_events on (device_id, last_ts) and takes MIN(device_platform) so that if two platforms tie at the exact same timestamp, the alphabetically earlier name wins.

    window_events from Example 2 for d80 (switched) and d90 (tied timestamp):
      d80 | 2026-04-14T10:00:00Z | ios
      d80 | 2026-04-15T11:00:00Z | tv        <-- MAX(ts) = 2026-04-15T11:00:00Z -> 'tv'
    
      d90 | 2026-04-15T15:00:00Z | tv        \__ both match MAX(ts);
      d90 | 2026-04-15T15:00:00Z | android   /   MIN(device_platform) -> 'android'
    
    yesterday_active AS (
        -- Distinct devices with at least one event yesterday (collapses duplicate events)
        SELECT DISTINCT w.device_id
        FROM window_events AS w
        CROSS JOIN bounds AS b
        WHERE w.event_date = b.yesterday
    ),
    today_active AS (
        -- Distinct devices with at least one event today
        SELECT DISTINCT w.device_id
        FROM window_events AS w
        CROSS JOIN bounds AS b
        WHERE w.event_date = b.today
    ),
    last_event AS (
        -- Latest timestamp per device inside the two-day window
        SELECT device_id, MAX(ts) AS last_ts
        FROM window_events
        GROUP BY device_id
    ),
    device_label AS (
        -- Assign exactly one platform per device: latest event, breaking timestamp ties alphabetically
        SELECT w.device_id, MIN(w.device_platform) AS device_platform
        FROM window_events AS w
        JOIN last_event AS l
            ON l.device_id = w.device_id
           AND l.last_ts = w.ts
        GROUP BY w.device_id
    ),
    
  6. Step 3 in SQL: classify devices into new, retained, and churned

    Now each bucket translates directly from its English definition into a join on device sets: - new_devices: in today_active and first_seen.first_date = bounds.today. - retained_devices: in both today_active and yesterday_active (INNER JOIN). - churned_devices: in yesterday_active and missing from today_active. We write this as an anti-join (LEFT JOIN today_active ... WHERE t.device_id IS NULL), which is safer than NOT IN (SELECT ...) because NOT IN returns zero rows whenever the subquery contains a single NULL.

    Can a device appear in two buckets? Never: - churned requires not being active today, while new and retained require being active today. - new requires first_date = today, while retained requires an event yesterday (first_date <= yesterday).

    Because the three sets cannot overlap, UNION ALL in flags stacks them without creating duplicate devices:

    new_devices AS (
        -- Active today AND never seen before today
        SELECT t.device_id
        FROM today_active AS t
        JOIN first_seen AS f
            ON f.device_id = t.device_id
        CROSS JOIN bounds AS b
        WHERE f.first_date = b.today
    ),
    retained_devices AS (
        -- Active on both yesterday and today
        SELECT t.device_id
        FROM today_active AS t
        JOIN yesterday_active AS y
            ON y.device_id = t.device_id
    ),
    churned_devices AS (
        -- Anti-join: active yesterday, missing from today_active
        SELECT y.device_id
        FROM yesterday_active AS y
        LEFT JOIN today_active AS t
            ON t.device_id = y.device_id
        WHERE t.device_id IS NULL
    ),
    flags AS (
        -- The three buckets are mutually exclusive, so UNION ALL lists each counted device once
        SELECT device_id, 1 AS is_new, 0 AS is_retained, 0 AS is_churn FROM new_devices
        UNION ALL
        SELECT device_id, 0, 1, 0 FROM retained_devices
        UNION ALL
        SELECT device_id, 0, 0, 1 FROM churned_devices
    ),
    
  7. Step 4 in SQL: roll up overall and per-platform counts

    Next, labeled joins flags to device_label so every counted device has its single platform name alongside its 0/1 indicators. Notice that resurrected devices never entered flags, so a platform whose only visitor today was resurrected will not produce an all-zero platform row.

    To build both the 'ALL' summary row and the per-platform rows in standard SQLite (which has no GROUPING SETS), totals combines two aggregations with UNION ALL: 1. No GROUP BY for 'ALL': in SQL, SELECT SUM(...) FROM empty_table with no GROUP BY always returns 1 row containing NULLs, and COALESCE(SUM(...), 0) turns those NULLs into 0s. That guarantees the 'ALL' row exists even when events is completely empty! 2. GROUP BY device_platform for each platform present in labeled.

    Finally, compute net_users and sort 'ALL' first using a CASE expression:

    labeled AS (
        -- Attach each counted device's single platform label
        SELECT d.device_platform, f.is_new, f.is_retained, f.is_churn
        FROM flags AS f
        JOIN device_label AS d
            ON d.device_id = f.device_id
    ),
    totals AS (
        -- Aggregating without GROUP BY guarantees one 'ALL' row even when labeled is empty
        SELECT
            'ALL' AS device_platform,
            COALESCE(SUM(is_new), 0) AS new_users,
            COALESCE(SUM(is_retained), 0) AS retained_users,
            COALESCE(SUM(is_churn), 0) AS churn_users
        FROM labeled
        UNION ALL
        SELECT
            device_platform,
            SUM(is_new) AS new_users,
            SUM(is_retained) AS retained_users,
            SUM(is_churn) AS churn_users
        FROM labeled
        GROUP BY device_platform
    )
    SELECT
        b.today AS event_date,
        t.device_platform,
        t.new_users,
        t.retained_users,
        t.churn_users,
        t.new_users + t.retained_users - t.churn_users AS net_users
    FROM totals AS t
    CROSS JOIN bounds AS b
    -- Put the overall 'ALL' row first, then sort platforms alphabetically
    ORDER BY CASE WHEN t.device_platform = 'ALL' THEN 0 ELSE 1 END, t.device_platform
    
  8. Complete solution

    Putting the entire query inside QUERY in solution.py gives the complete, runnable solution:

    # CTE pipeline overview and data shapes:
    # 1. bounds: 1 row [today, yesterday] derived from :today using SQLite calendar math.
    # 2. first_seen: [device_id, first_date] across ALL history so returning old users are never marked new.
    # 3. window_events: [device_id, event_date, ts, device_platform] restricted to yesterday and today,
    #    dropping NULL device_ids and mapping NULL platforms to 'unknown'.
    # 4. yesterday_active / today_active: [device_id] sets deduplicated with SELECT DISTINCT.
    # 5. last_event + device_label: [device_id, device_platform] picking each device's latest timestamp
    #    in the 2-day window without window functions, breaking timestamp ties alphabetically via MIN().
    # 6. new_devices / retained_devices / churned_devices: three mutually exclusive [device_id] sets;
    #    churn uses a LEFT JOIN ... IS NULL anti-join so NULLs can never blank out the result.
    # 7. flags + labeled: [device_platform, is_new, is_retained, is_churn] with one row per counted device.
    # 8. totals: 'ALL' row (no GROUP BY + COALESCE so empty days still emit 0s) UNION ALL per-platform rows.
    QUERY = """
    WITH bounds AS (
        -- Compute today and yesterday in UTC calendar dates (handles month and leap-year rollovers)
        SELECT DATE(:today) AS today, DATE(:today, '-1 day') AS yesterday
    ),
    first_seen AS (
        -- Scan full event history to find the first UTC date each device ever appeared
        SELECT device_id, MIN(DATE(ts)) AS first_date
        FROM events
        WHERE device_id IS NOT NULL
        GROUP BY device_id
    ),
    window_events AS (
        -- Keep only yesterday's and today's valid events and normalize NULL platform to 'unknown'
        SELECT
            e.device_id,
            DATE(e.ts) AS event_date,
            e.ts,
            COALESCE(e.device_platform, 'unknown') AS device_platform
        FROM events AS e
        CROSS JOIN bounds AS b
        WHERE e.device_id IS NOT NULL
          AND DATE(e.ts) IN (b.yesterday, b.today)
    ),
    yesterday_active AS (
        -- Distinct devices with at least one event yesterday (collapses duplicate events)
        SELECT DISTINCT w.device_id
        FROM window_events AS w
        CROSS JOIN bounds AS b
        WHERE w.event_date = b.yesterday
    ),
    today_active AS (
        -- Distinct devices with at least one event today
        SELECT DISTINCT w.device_id
        FROM window_events AS w
        CROSS JOIN bounds AS b
        WHERE w.event_date = b.today
    ),
    last_event AS (
        -- Latest timestamp per device inside the two-day window
        SELECT device_id, MAX(ts) AS last_ts
        FROM window_events
        GROUP BY device_id
    ),
    device_label AS (
        -- Assign exactly one platform per device: latest event, breaking timestamp ties alphabetically
        SELECT w.device_id, MIN(w.device_platform) AS device_platform
        FROM window_events AS w
        JOIN last_event AS l
            ON l.device_id = w.device_id
           AND l.last_ts = w.ts
        GROUP BY w.device_id
    ),
    new_devices AS (
        -- Active today AND never seen before today
        SELECT t.device_id
        FROM today_active AS t
        JOIN first_seen AS f
            ON f.device_id = t.device_id
        CROSS JOIN bounds AS b
        WHERE f.first_date = b.today
    ),
    retained_devices AS (
        -- Active on both yesterday and today
        SELECT t.device_id
        FROM today_active AS t
        JOIN yesterday_active AS y
            ON y.device_id = t.device_id
    ),
    churned_devices AS (
        -- Anti-join: active yesterday, missing from today_active
        SELECT y.device_id
        FROM yesterday_active AS y
        LEFT JOIN today_active AS t
            ON t.device_id = y.device_id
        WHERE t.device_id IS NULL
    ),
    flags AS (
        -- The three buckets are mutually exclusive, so UNION ALL lists each counted device once
        SELECT device_id, 1 AS is_new, 0 AS is_retained, 0 AS is_churn FROM new_devices
        UNION ALL
        SELECT device_id, 0, 1, 0 FROM retained_devices
        UNION ALL
        SELECT device_id, 0, 0, 1 FROM churned_devices
    ),
    labeled AS (
        -- Attach each counted device's single platform label
        SELECT d.device_platform, f.is_new, f.is_retained, f.is_churn
        FROM flags AS f
        JOIN device_label AS d
            ON d.device_id = f.device_id
    ),
    totals AS (
        -- Aggregating without GROUP BY guarantees one 'ALL' row even when labeled is empty
        SELECT
            'ALL' AS device_platform,
            COALESCE(SUM(is_new), 0) AS new_users,
            COALESCE(SUM(is_retained), 0) AS retained_users,
            COALESCE(SUM(is_churn), 0) AS churn_users
        FROM labeled
        UNION ALL
        SELECT
            device_platform,
            SUM(is_new) AS new_users,
            SUM(is_retained) AS retained_users,
            SUM(is_churn) AS churn_users
        FROM labeled
        GROUP BY device_platform
    )
    SELECT
        b.today AS event_date,
        t.device_platform,
        t.new_users,
        t.retained_users,
        t.churn_users,
        t.new_users + t.retained_users - t.churn_users AS net_users
    FROM totals AS t
    CROSS JOIN bounds AS b
    -- Put the overall 'ALL' row first, then sort platforms alphabetically
    ORDER BY CASE WHEN t.device_platform = 'ALL' THEN 0 ELSE 1 END, t.device_platform
    """
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture taking attendance at a gym on Tuesday (yesterday) and Wednesday (today), while also keeping a master membership ledger from opening day (first_seen). Someone who walks in on Wednesday for the very first time in the ledger is new; someone on both Tuesday's and Wednesday's sign-in sheets is retained; and someone on Tuesday's sheet who does not show up on Wednesday is churned. (A resurrected user — someone who visited weeks ago, skipped Tuesday, and returned on Wednesday — fits none of the three definitions.) Finally, to report counts by room (device_platform) so that the rooms add up to the building total ('ALL'), you give each person one badge matching the last room they used across those two days.

A naive single-pass SELECT ... GROUP BY device_platform fails in three ways at once. First, counting raw event rows instead of distinct device_ids counts a viewer who paused or clicked five times as five users. Second, filtering the log to Tuesday and Wednesday before computing MIN(DATE(ts)) erases older history and mislabels every resurrected user as brand-new. Third, grouping directly by (device_id, device_platform) counts a user who watched on ios Tuesday and tv Wednesday twice, so the platform rows no longer sum to 'ALL'.

We solve this cleanly with CTEs (Common Table Expressions — named WITH subqueries that act like small, sequential temporary tables). Trace three devices for :today = '2026-04-15' (yesterday = '2026-04-14'): 1. Raw events: d10 on 04-14 and 04-15 (ios), d50 on 04-14 (android), and d40 on 04-15 (web). 2. first_seen records d10 -> 04-14, d50 -> 04-14, d40 -> 04-15; yesterday_active = {d10, d50} and today_active = {d10, d40}. 3. Set joins classify d40 as new (active today and first_date = 04-15), d10 as retained (in both active sets), and d50 as churn via an anti-join (a LEFT JOIN keeping rows where the right-hand match is NULL, meaning active yesterday but absent today). 4. Summing the 0/1 flags once overall ('ALL': new=1, retained=1, churn=1, net=1) and once per platform produces the exact breakdown.

Complexity

Let E be the total number of event rows in history, U the number of distinct devices ever seen, W the number of events on yesterday and today, and D the number of distinct devices active in that two-day window.

  • Time: O(E) with hash aggregation (or O(E log E) if the engine sorts). Scanning events to compute first_seen touches all E historical rows once, which dominates runtime. Filtering window_events, deduplicating yesterday_active and today_active, finding MAX(ts), and joining device sets all operate only on the two-day window in O(W) time, and the final rollup over counted devices takes O(D) time.
  • Space: O(U + D). first_seen holds one (device_id, first_date) pair for each of the U all-time devices (unless the optimizer pushes the join with today_active down), while yesterday_active, today_active, device_label, and flags each store at most D rows.

In a production data warehouse, two optimizations avoid scanning E rows every day: - Maintain an incremental device_first_seen(device_id, first_date) table updated daily with newly seen devices, reducing the daily job to reading only two date partitions. - Filter raw timestamps directly (ts >= '2026-04-14T00:00:00Z' AND ts < '2026-04-16T00:00:00Z') to enable partition pruning (the query engine's ability to skip reading storage files outside the requested date range), which wrapping a column in DATE(ts) can block in some engines.

Edge cases

  • Resurrected devices: A device active on 2026-04-10 and 2026-04-15 (but not 2026-04-14, like d70 in Example 2) is neither new, retained, nor churned, and does not create an all-zero row for its platform.
  • Future events in the table: When backfilling :today = '2026-04-15', an event on 2026-04-16 (like d60 in Example 1) lies outside window_events and does not prevent d60 from being churned on 2026-04-15. Because :today is parameterized, each run is idempotent (rerunning it on the same inputs always produces the exact same result).
  • UTC midnight boundaries: Events at 2026-04-14T23:45:00Z and 2026-04-15T00:20:00Z (d10 in Example 1) sit 35 minutes apart on different UTC dates, making d10 retained rather than churned.
  • Platform switches and timestamp ties: A device switching from ios yesterday to tv today (d80 in Example 2) is counted once under tv; simultaneous events at MAX(ts) (d90 in Example 2) break ties alphabetically via MIN(device_platform).
  • NULLs and duplicates: Rows with device_id IS NULL are ignored, device_platform IS NULL becomes 'unknown', and identical duplicate events collapse via SELECT DISTINCT.
  • Empty log or empty window: Aggregating labeled without GROUP BY plus COALESCE(SUM(...), 0) still returns the single row (:today, 'ALL', 0, 0, 0, 0).
  • Month and leap-year boundaries: DATE('2024-03-01', '-1 day') evaluates to '2024-02-29', whereas naive string arithmetic fails.

Common mistakes

  • Computing first_seen inside window_events instead of full history: Any returning user who skipped yesterday then has MIN(event_date) = today inside the window and is falsely counted as a new user.
  • Counting events (COUNT(*)) instead of distinct devices: One active viewer firing 20 play or search events gets counted as 20 retained or new users.
  • Grouping active events by (device_id, device_platform) before bucketing: A user who switches platforms between yesterday and today gets counted on both platforms (or as churned on one and active on the other), breaking the invariant that platform rows sum to 'ALL'.
  • Writing ts BETWEEN '2026-04-14' AND '2026-04-15' on timestamps: SQL treats '2026-04-15' as 2026-04-15 00:00:00, silently dropping every event after midnight on today.
  • Using NOT IN (SELECT device_id ...) for churn: In SQL's three-valued logic, if the subquery ever produces a NULL, x NOT IN (...) evaluates to UNKNOWN for every row and churn_users drops to 0. Always prefer LEFT JOIN ... WHERE right.id IS NULL or NOT EXISTS.
  • Interpreting net_users as DAU(today) - DAU(yesterday): In Example 1, DAU rises from 3 on 04-14 (d10, d50, d60) to 4 on 04-15 (d10, d20, d30, d40, change +1), whereas the defined net_users = 3 + 1 - 2 equals 2.

Follow-up questions

  • How would you generalize this query to produce daily metrics across an entire multi-day date window in a single execution? First build device_days (SELECT DISTINCT device_id, DATE(ts) AS day FROM events WHERE device_id IS NOT NULL) and first_seen (MIN(day) per device). Self-join device_days AS cur with LEFT JOIN device_days AS prev ON prev.device_id = cur.device_id AND prev.day = DATE(cur.day, '-1 day') to flag new (cur.day = first_date) and retained (prev.device_id IS NOT NULL) on cur.day. Then UNION ALL a second LEFT JOIN from yesterday to today (WHERE today.device_id IS NULL) dated DATE(yesterday.day, '+1 day') to emit churn rows, and filter the final output to your reporting date range.
  • How could you incorporate returning dormant users and verify daily metric consistency automatically? Add resurrected_devices for devices in today_active, absent from yesterday_active, with first_date < today. Once all four buckets exist, assert two exact accounting identities every day: new + retained + resurrected = DAU(today) and retained + churn = DAU(yesterday). Any mismatch immediately flags duplicate rows in device_first_seen, timezone bugs, or a missing daily partition.
  • What adjustments are needed if stakeholders request week-over-week retention and churn instead of daily figures? Replace the two 1-day buckets with two non-overlapping 7-day windows: this_week ([:today - 6 days, :today]) and last_week ([:today - 13 days, :today - 7 days]). A device is new if its all-time first_date falls inside this_week, retained if active in both 7-day windows, and churned if active in last_week but not this_week, with platform taken from its latest event across the 14-day span.

Follow-up questions

Similar questions

More Tubi interview questions

All 11 Tubi questions →