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 samedevice_idon the same UTC date count that device once. - Bucket definitions (for
:today):new_users: distinct devices active ontodaywhose earliest UTCDATE(ts)across the entireeventstable equalstoday.retained_users: distinct devices active on bothyesterdayandtoday.churn_users: distinct devices active onyesterdayand not active ontoday.net_users:new_users + retained_users - churn_users.- (Note: a returning dormant device—seen strictly before
yesterday, inactive onyesterday, and active ontoday—belongs to none of the three buckets.)
- Single-platform attribution: Every device active in
(yesterday, today)is assigned a single platform equal toCOALESCE(device_platform, 'unknown')from its latest event (MAX(ts)) within(yesterday, today). If multiple events share that exactMAX(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)withevent_date = today. Output the overall summary row (device_platform = 'ALL') first—returning0for each count when no devices qualify—followed in ascending alphabetical order by one row perdevice_platformthat 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:todayas its named parameter. eventsmay contain0rows, duplicate rows,NULLvalues indevice_idordevice_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'hasyesterday = '2024-02-29').
Step-by-step walkthrough
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:todayagainst 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_usersNotice a subtle trap in the formula:
net_usersis notDAU(today) - DAU(yesterday). Why? Today's daily active users (DAU) equalnew + retained + resurrected, whereas yesterday's equalretained + churn. Their difference isnew + resurrected - churn, which leaves outretainedand includesresurrected. 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'rowTie at the exact same latest timestamp Pick the alphabetically first platform ( MIN(device_platform))Makes the output 100% deterministic without needing window functions device_platformisNULLReplace with 'unknown'Keeps the device in both the 'ALL'total and a visible'unknown'breakdown rowdevice_idisNULLIgnore 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, with0s if no devices qualifyGives dashboards one consistent table even on an empty day 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 webTwo rows are especially instructive: -
d10has two events only 35 minutes apart (2026-04-14T23:45:00Zand2026-04-15T00:20:00Z). Because they cross UTC midnight,d10is active on both UTC days and counts as retained. In US Pacific time (UTC-7), both timestamps would land on2026-04-14andd10would become churned. -d60comes back on2026-04-16, which is after:today. Relative to2026-04-15,d60was 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 0Check the arithmetic: across the three platforms,
new = 1 + 1 + 1 = 3,retained = 0 + 1 + 0 = 1,churn = 1 + 0 + 1 = 2, andnet = 0 + 2 + 0 = 2. Every column adds up to'ALL'.Plan the query as a pipeline of small CTEs
Trying to compute
first-ever date,active yesterday,active today, andlatest platforminside one giantSELECT ... GROUP BYquickly tangles row-level events with user-level cohorts. Instead, we use CTEs (Common Table Expressions — namedWITHsubqueries 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 rowsWorking with sets of distinct
device_ids guarantees that duplicate events or power users with 500 clicks never inflate user counts.Step 1 in SQL: compute date bounds, first-ever day, and the two-day window
First,
boundscomputestodayandyesterdayfrom:todayusing SQLite'sDATE(:today, '-1 day')(in ANSI/Postgres/BigQuery SQL, writeCAST(:today AS DATE) - INTERVAL '1' DAY). Using calendar arithmetic instead of string slicing handles month rollovers and leap years like2024-03-01 -> 2024-02-29.Next,
first_seenmust scan the entireeventstable, not just the two-day window. If you filteredeventsto04-14and04-15first, a user who visited on04-10, skipped04-14, and returned on04-15(liked70in Example 2) would falsely look like a brand-new user. Onlywindow_eventsrestricts rows toyesterdayandtoday.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) ),Step 2 in SQL: deduplicate active devices and pick one platform per device
From
window_events,SELECT DISTINCT device_idgives 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_eventfinds each device's latest timestampMAX(ts)inside the two-day window. 2.device_labeljoins back towindow_eventson(device_id, last_ts)and takesMIN(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 ),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: intoday_activeandfirst_seen.first_date = bounds.today. -retained_devices: in bothtoday_activeandyesterday_active(INNER JOIN). -churned_devices: inyesterday_activeand missing fromtoday_active. We write this as an anti-join (LEFT JOIN today_active ... WHERE t.device_id IS NULL), which is safer thanNOT IN (SELECT ...)becauseNOT INreturns zero rows whenever the subquery contains a singleNULL.Can a device appear in two buckets? Never: -
churnedrequires not being active today, whilenewandretainedrequire being active today. -newrequiresfirst_date = today, whileretainedrequires an event yesterday (first_date <= yesterday).Because the three sets cannot overlap,
UNION ALLinflagsstacks 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 ),Step 4 in SQL: roll up overall and per-platform counts
Next,
labeledjoinsflagstodevice_labelso every counted device has its single platform name alongside its0/1indicators. Notice that resurrected devices never enteredflags, 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 noGROUPING SETS),totalscombines two aggregations withUNION ALL: 1. NoGROUP BYfor'ALL': in SQL,SELECT SUM(...) FROM empty_tablewith noGROUP BYalways returns 1 row containingNULLs, andCOALESCE(SUM(...), 0)turns thoseNULLs into0s. That guarantees the'ALL'row exists even wheneventsis completely empty! 2.GROUP BY device_platformfor each platform present inlabeled.Finally, compute
net_usersand sort'ALL'first using aCASEexpression: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_platformComplete solution
Putting the entire query inside
QUERYinsolution.pygives 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 (orO(E log E)if the engine sorts). Scanningeventsto computefirst_seentouches allEhistorical rows once, which dominates runtime. Filteringwindow_events, deduplicatingyesterday_activeandtoday_active, findingMAX(ts), and joining device sets all operate only on the two-day window inO(W)time, and the final rollup over counted devices takesO(D)time. - Space:
O(U + D).first_seenholds one(device_id, first_date)pair for each of theUall-time devices (unless the optimizer pushes the join withtoday_activedown), whileyesterday_active,today_active,device_label, andflagseach store at mostDrows.
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-10and2026-04-15(but not2026-04-14, liked70in 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 on2026-04-16(liked60in Example 1) lies outsidewindow_eventsand does not preventd60from being churned on2026-04-15. Because:todayis 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:00Zand2026-04-15T00:20:00Z(d10in Example 1) sit 35 minutes apart on different UTC dates, makingd10retained rather than churned. - Platform switches and timestamp ties: A device switching from
iosyesterday totvtoday (d80in Example 2) is counted once undertv; simultaneous events atMAX(ts)(d90in Example 2) break ties alphabetically viaMIN(device_platform). - NULLs and duplicates: Rows with
device_id IS NULLare ignored,device_platform IS NULLbecomes'unknown', and identical duplicate events collapse viaSELECT DISTINCT. - Empty log or empty window: Aggregating
labeledwithoutGROUP BYplusCOALESCE(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_seeninsidewindow_eventsinstead of full history: Any returning user who skipped yesterday then hasMIN(event_date) = todayinside the window and is falsely counted as a new user. - Counting events (
COUNT(*)) instead of distinct devices: One active viewer firing 20playorsearchevents 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'as2026-04-15 00:00:00, silently dropping every event after midnight ontoday. - Using
NOT IN (SELECT device_id ...)for churn: In SQL's three-valued logic, if the subquery ever produces aNULL,x NOT IN (...)evaluates toUNKNOWNfor every row andchurn_usersdrops to0. Always preferLEFT JOIN ... WHERE right.id IS NULLorNOT EXISTS. - Interpreting
net_usersasDAU(today) - DAU(yesterday): In Example 1,DAUrises from 3 on04-14(d10, d50, d60) to 4 on04-15(d10, d20, d30, d40, change+1), whereas the definednet_users = 3 + 1 - 2equals2.
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) andfirst_seen(MIN(day)per device). Self-joindevice_days AS curwithLEFT JOIN device_days AS prev ON prev.device_id = cur.device_id AND prev.day = DATE(cur.day, '-1 day')to flagnew(cur.day = first_date) andretained(prev.device_id IS NOT NULL) oncur.day. ThenUNION ALLa secondLEFT JOINfromyesterdaytotoday(WHERE today.device_id IS NULL) datedDATE(yesterday.day, '+1 day')to emitchurnrows, 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_devicesfor devices intoday_active, absent fromyesterday_active, withfirst_date < today. Once all four buckets exist, assert two exact accounting identities every day:new + retained + resurrected = DAU(today)andretained + churn = DAU(yesterday). Any mismatch immediately flags duplicate rows indevice_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]) andlast_week([:today - 13 days, :today - 7 days]). A device isnewif its all-timefirst_datefalls insidethis_week,retainedif active in both 7-day windows, andchurnedif active inlast_weekbut notthis_week, with platform taken from its latest event across the 14-day span.
Follow-up questions
- How would you generalize this query to produce daily metrics across an entire multi-day date window in a single execution?
- How could you incorporate returning dormant users and verify daily metric consistency automatically?
- What adjustments are needed if stakeholders request week-over-week retention and churn instead of daily figures?
Similar questions
- Statistical Sample Size and Power Drivers
- Simulate a Read-Through TTL Cache
- ML Foundations, Production Tuning, and Recommender Systems
- Multi-Metric Experiment Design and Launch Trade-Off Communication
- From-Scratch K-Means Clustering vs. Gaussian Mixture Models
- Core ML Screen: Decision Trees, Optimization, Metrics, and Attention
More Tubi interview questions
- Simulate a Read-Through TTL Cache Medium
- Thread-Safe TTL Cache with Single-Flight Loading Medium
- Statistical Sample Size and Power Drivers Hard Pro
- ML Foundations, Production Tuning, and Recommender Systems Medium Pro
- Multi-Metric Experiment Design and Launch Trade-Off Communication Hard Pro
- From-Scratch K-Means Clustering vs. Gaussian Mixture Models Medium Pro
- Streaming Movie Recommendation Pipeline and Model (AI-Assisted) Medium Pro
- Designing Artwork Selection for a Video Streaming Library Medium Pro
- Core ML Screen: Decision Trees, Optimization, Metrics, and Attention Medium Pro
- Proportional Random Index Sampler Medium Pro