Advanced SQL: Metric Monitoring, Anomaly Detection, and Data Correctness at Scale Questions
SQL for monitoring a business or operational metric over time and catching when it is wrong or behaving abnormally, as distinct from the mechanics of the SQL constructs used to compute it (window function syntax, frame semantics, CTEs, and subqueries are covered by the companion topic Advanced SQL: Window Functions, CTEs, and Subqueries), from defining and computing cohort retention, funnel conversion, DAU/WAU/MAU, and lifetime value themselves (covered by the companion topics User Retention & Engagement, Conversion Funnel Optimization, and SQL for Data Analysis), and from sessionization via inactivity-gap detection (also covered by the companion window-functions topic). Covers rolling-window anomaly and change-point detection (z-score and threshold-based, including seasonality-aware baselines), testing whether a period-over-period change in a rate metric is statistically significant versus noise, decomposing a metric's change into which segments drove it, average revenue per user (ARPU) at both a simple and a rolling/at-scale altitude, keeping cumulative and rolling metrics correct against missing dates, late-arriving or out-of-order events, and incremental (not full-recompute) materialization at very large scale, approximate-distinct (HyperLogLog) computation, standalone timezone/daylight-saving-aware day bucketing, Kaplan-Meier-style survival curves computed in pure SQL, and multi-state subscription churn and retention (renewals, expansions, downgrades, and pauses at the plan level, not just customer presence/absence).
Propose an approach to compute an incremental cumulative metric (for example, running revenue per user) in BigQuery without recomputing the entire history nightly. Describe the table design (partitioning, clustering), the merge/upsert pattern you would use, and how you would handle corrections that land in already-processed historical partitions.
Sample Answer
Direct answer
Maintain the cumulative metric as an incrementally-updated table keyed on the entity (for example, per user), where each run only touches the partitions affected by NEW or CORRECTED data since the last run, using a merge/upsert rather than recomputing the running total from the full history every time.
Structured elaboration
- Table design: partition (or cluster) the maintained cumulative table by the entity key and, if the source data itself is naturally date-partitioned, by date as well, so a given run only needs to read the partitions that actually changed.
- Merge/upsert pattern: for each entity affected by new data since the last run, recompute that entity's cumulative value by adding the new increment to its PREVIOUSLY STORED cumulative value, rather than re-summing the entity's entire history. This turns an O(full history) recompute into an O(new data) update.
- Handling corrections to historical partitions: if a correction lands against data from months ago (a late refund, a corrected transaction amount), the incremental approach above breaks, because it assumed only NEW increments need to be added, not that OLD increments might change. The fix: when a correction is detected, recompute the cumulative value starting from the corrected partition forward, not just apply the delta at the current date, since every day's running total downstream of the correction is now stale. This is more expensive than a routine incremental update but still far cheaper than a full history recompute, since it only replays forward from the earliest affected date rather than from the beginning of time.
- Detecting that a correction happened at all: usually requires either an explicit "corrected records" feed from the source system, or a reconciliation check comparing a freshly-computed total for an old period against the currently stored one and flagging a mismatch.
Worked example
Consider a per-user cumulative revenue table maintained incrementally. On a normal day, a new $50 order for user 42 arrives; the maintained pipeline reads user 42's current stored cumulative value (say $1,200), adds $50, and writes back $1,250, touching only that one row. Contrast this with a correction: a $30 refund is discovered against an order from 60 days ago for the same user. A pure "add the new increment" pipeline would incorrectly just subtract $30 from TODAY's cumulative value, leaving every day BETWEEN the refunded order and today reporting a cumulative total that is $30 too high (since the running total at each of those intermediate dates was itself computed by summing everything up to that point, and none of those historical days ever saw the correction). The correct handling replays the cumulative sum forward starting from the date of the original order 60 days ago, correcting that day's cumulative total and every day after it through today, using the corrected order-level data as the source of truth.
Trade-offs & pitfalls
- The single biggest defect in a naive incremental design is exactly the correction case above: an interviewer probing this question is very likely testing whether the candidate's design silently mishandles a correction to old data, not just whether they know how to add up numbers.
- Detecting corrections is often the harder engineering problem than applying them, especially against a source system that doesn't clearly flag which historical records changed; a reconciliation job comparing recomputed vs. stored totals on a sample of old partitions is a common pragmatic mitigation.
- Replaying forward from a correction point is still bounded work (from the correction date to today), not unbounded, which is the entire point of this design relative to a full nightly recompute; but it does mean a correction to very old data is proportionally more expensive to apply than one to recent data.
Compute DAU and MAU per country for each day and the stickiness metric DAU/MAU using rolling 30-day windows. Additionally, implement a statistical change detection (for example a simple rolling z-test or CUSUM) to flag significant drops in stickiness per country. Provide SQL and explain assumptions.
Sample Answer
Direct answer
Compute daily DAU and rolling-30-day MAU per country in SQL exactly as any DAU/MAU pipeline would, then layer a rolling z-test on top: for each day, compare that day's DAU/MAU stickiness ratio against the mean and standard deviation of the trailing 7 days, flagging a drop as significant only when it clears a z-score threshold, since a fixed percentage-drop threshold applied uniformly across countries of very different population sizes will systematically over-flag small countries (where ordinary sampling noise is proportionally larger) and under-flag large ones.
Structured elaboration
SQL: DAU, MAU, and stickiness per country per day. For each (country, day), dau = COUNT(DISTINCT user_id) WHERE event_date = day, mau = COUNT(DISTINCT user_id) WHERE event_date BETWEEN day-29 AND day, stickiness = dau/mau; computed as a per-country time series, since the whole point of segmenting by country is that each one needs its own independent baseline and its own independent change-detection run.
Why a rolling z-test, not a fixed percentage-drop rule. A rule like "flag if stickiness drops more than 10% day over day" ignores that ordinary day-to-day noise in a metric derived from binomial-like sampling scales with population size: a country with 150 active users has proportionally MORE natural day-to-day variance in its ratio than a country with 1.5 million, so the same fixed percentage threshold will fire far more often, on pure noise, for the small country. A z-test compares each day's value against a LOCALLY-estimated (same country, recent trailing window) mean and standard deviation, which automatically adapts to each country's own natural noise level instead of applying one global threshold everywhere.
The rolling z-test mechanics. For day t, using the trailing 7 days t−7..t−1 (excluding day t itself, so the baseline is not contaminated by the very day being tested): zt=st−7:t−1xt−xˉt−7:t−1, flagging ∣zt∣>2 as a candidate significant change (a common, simple threshold; the exact cutoff is itself a tunable parameter that trades false positives against detection sensitivity).
Assumptions. The trailing-7-day baseline assumes the metric is not itself on a strong trend during the baseline window (a genuinely trending baseline inflates its own variance estimate and can mask a subsequent real break); a more robust production version might detrend first or use a longer, seasonally-aware baseline. The z-test also assumes day-to-day values are reasonably independent, which is an approximation (consecutive days' MAU windows overlap heavily by construction, since MAU is a 30-day rolling figure, so consecutive days' stickiness values are NOT fully independent of each other), a real limitation to name rather than pretend away.
Worked example
A pinned, reproducible dataset: a fixed pool of 150 US users, with a deterministic random SEED controlling which subset is active each day (drawn from the same 150-user pool every day, so MAU stabilizes rather than growing without bound). Days 1-14 (Jan 1-14): 30% of the pool active daily (~45 users/day). Days 15-20 (Jan 15-20): a genuine injected regression to 15% of the pool (~22 users/day).
import sqlite3, statistics, random, datetime
random.seed(42)
conn = sqlite3.connect(':memory:')
cur = conn.cursor()
cur.execute("CREATE TABLE events (user_id INTEGER, country TEXT, event_date TEXT)")
pool = list(range(1, 151))
rows, base = [], datetime.date(2026, 1, 1)
for day_idx in range(20):
d = base + datetime.timedelta(days=day_idx)
active_share = 0.30 if day_idx < 14 else 0.15
n_active = round(len(pool) * active_share)
for u in random.sample(pool, n_active):
rows.append((u, 'US', d.isoformat()))
cur.executemany("INSERT INTO events VALUES (?,?,?)", rows)
conn.commit()
cur.execute("SELECT DISTINCT event_date FROM events ORDER BY event_date")
days = [r[0] for r in cur.fetchall()]
series = []
for d in days:
cur.execute("SELECT COUNT(DISTINCT user_id) FROM events WHERE event_date = ?", (d,))
dau = cur.fetchone()[0]
cur.execute("SELECT COUNT(DISTINCT user_id) FROM events WHERE event_date <= ? AND event_date > date(?, '-29 days')", (d, d))
mau = cur.fetchone()[0]
series.append((d, dau, mau, round(dau/mau, 4)))
stick = [r[3] for r in series]
print("date stickiness z-score flag")
for i in range(7, len(stick)):
window = stick[i-7:i]
mean, sd = statistics.mean(window), statistics.pstdev(window)
z = (stick[i]-mean)/sd if sd > 0 else None
flag = "FLAG" if (z is not None and abs(z) > 2) else ""
print(days[i], stick[i], round(z,2) if z is not None else None, flag)
Output (actually executed, showing the days spanning the injected break on Jan 15):
date stickiness z-score flag
2026-01-14 0.302 -1.04
2026-01-15 0.1477 -23.2 FLAG
2026-01-16 0.1477 -2.44 FLAG
2026-01-17 0.1477 -1.58
The rolling z-test correctly flags January 15th, the exact day the injected regression begins, with a large negative z-score, and continues to flag the 16th before the trailing baseline itself catches up to the new lower regime and the z-scores fall back under threshold. This is the genuine detection the exercise asks for: the 30% to 15% share change was injected as a KNOWN, deliberate break, and the z-test found it at the correct day, not a day early or late.
Trade-offs and pitfalls
- A single global percentage-drop threshold, run naively across every country regardless of population size, is the exact failure mode this z-test design exists to avoid; a small country's natural sampling noise can exceed a fixed 10% threshold on an ordinary day with no real change at all, while the same threshold might miss a real but proportionally smaller move in a huge country.
- The rolling baseline itself gets contaminated once the break has been in effect for more than the window length (7 days here), visible in the output as the z-scores fading back toward zero by January 17th even though the LOWER regime persists; a production system needs either a longer post-break cool-down before re-baselining, or a CUSUM-style approach (which accumulates evidence of a sustained shift rather than resetting its baseline every single day) specifically to avoid this "the alert stops firing just because enough days have passed" blind spot.
- Applying this per-country without a minimum-population floor risks running the whole apparatus on countries too small for even a locally-estimated baseline to be meaningful; a country with, say, fewer than 20-30 daily active users has too few underlying observations for a 7-day trailing mean/stdev to be a trustworthy reference, and such countries likely need a different (or simply suppressed) alerting treatment rather than the same z-test applied uniformly.
A metric such as daily revenue or a per-segment event count is monitored with a rolling N-day mean and standard deviation, flagging a day as anomalous when its z-score exceeds a threshold. Write the SQL, then explain two ways this naive approach breaks in practice: it fires false positives on days with genuine weekly seasonality (a Monday should be compared to prior Mondays, not to the raw trailing window), and the underlying mean/variance estimate itself gets noisy early in a series or for low-volume segments.
Sample Answer
Direct answer
A naive rolling z-score (mean and standard deviation over the trailing N days, current day included or not) breaks down whenever the metric has weekly seasonality, because it compares a day to a mixed population of weekdays and weekends rather than to its own kind of day. The fix is to compute the baseline per day-of-week: compare a Monday only to prior Mondays.
Structured elaboration
- Naive approach:
AVG/STDDEV_SAMPoverROWS BETWEEN 6 PRECEDING AND CURRENT ROW, ordered by date, thenz = (value - roll_mean) / roll_std. - Why it breaks: a 7-day window spanning both weekday and weekend values estimates a standard deviation that reflects the SIZE of the seasonal swing, not genuine day-to-day noise. That inflated standard deviation does two things at once: it makes structurally-low weekend days score a moderate, harmless-looking negative z (a false signal of concern where none exists), and it makes a real anomaly on a weekday look small relative to that inflated spread (a missed true anomaly).
- Fix: partition the window by day-of-week, ordered by date, so each day is compared only to its own recent history of the same weekday:
PARTITION BY EXTRACT(dow FROM day) ORDER BY day ROWS BETWEEN 4 PRECEDING AND 1 PRECEDING. - Remaining pitfalls even after the fix: a day-of-week baseline still needs several prior instances of that weekday before its own standard deviation is meaningful (same minimum-history guard as any rolling statistic), and it will not by itself catch a genuine change that happens to be a full week long, since day-of-week baselines are blind to same-weekday drift over a multi-week span.
Worked example
Five weeks of a metric with clean weekly seasonality (weekdays around 100-104, weekends around 40-42) and ONE planted real anomaly: a Friday reading of 130 where every other Friday in the series was 100-104. Concretely:
| week | Mon | Tue | Wed | Thu | Fri | Sat | Sun |
|---|---|---|---|---|---|---|---|
| 1 | 101 | 103 | 100 | 102 | 101 | 41 | 42 |
| 2 | 100 | 101 | 104 | 103 | 103 | 40 | 41 |
| 3 | 102 | 100 | 101 | 104 | 100 | 42 | 40 |
| 4 | 103 | 104 | 102 | 100 | 104 | 41 | 42 |
| 5 | 104 | 102 | 103 | 101 | 130 | 41 | 41 |
Naive rolling 7-day z-score on that Friday:
SELECT day, metric_value,
AVG(metric_value) OVER w AS roll_mean,
STDDEV_SAMP(metric_value) OVER w AS roll_std,
(metric_value - AVG(metric_value) OVER w) / STDDEV_SAMP(metric_value) OVER w AS z
FROM daily_metric
WINDOW w AS (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW)
gives roll_mean = 89.00, roll_std = 33.98, z = 1.21 -- computed directly from the trailing 7 calendar days ending on that Friday (week 4's Sat, Sun: 41, 42, then week 5's Mon-Fri: 104, 102, 103, 101, 130): mean = (41+42+104+102+103+101+130)/7 = 623/7 = 89.00, and the sample standard deviation of those same 7 values is 33.98, comfortably under any reasonable alert threshold. The genuine 25-30% spike is missed, because the naive window's standard deviation is inflated to 33.98 by mixing weekday and weekend values.
Day-of-week-adjusted baseline on the identical Friday:
SELECT day, metric_value,
AVG(metric_value) OVER w AS dow_mean,
STDDEV_SAMP(metric_value) OVER w AS dow_std,
(metric_value - AVG(metric_value) OVER w) / STDDEV_SAMP(metric_value) OVER w AS z_dow
FROM daily_metric
WINDOW w AS (PARTITION BY dayofweek(day) ORDER BY day ROWS BETWEEN 4 PRECEDING AND 1 PRECEDING)
gives dow_mean = 102.00, dow_std = 1.826, z_dow = 15.34 -- from the prior 4 Fridays in the table (weeks 1-4: 101, 103, 100, 104): mean = 408/4 = 102.00, sample standard deviation 1.826, and z_dow = (130 - 102.00) / 1.826 = 15.34. Comparing only to prior Fridays gives a tight, honest standard deviation and correctly flags this as a dramatic outlier. On week 5's Saturday (41), an ordinary non-anomalous weekend day in the same table: the naive method's trailing 7-day window shifted one day later ([42, 104, 102, 103, 101, 130, 41], the same mean 89.00 and std 33.98 as above) reports z = (41 - 89.00) / 33.98, which works out to roughly -1.41 (looks like a mild, spurious negative signal), while the day-of-week method, using the prior 4 Saturdays (41, 40, 42, 41, mean 41.00, std 0.816), reports z_dow = (41 - 41.00) / 0.816 = 0.00 exactly (correctly recognizing that value as completely normal for that day type).
Trade-offs & pitfalls
- The naive method is not just "less accurate", it fails in both directions at once: false positives on structurally low days, false negatives on real anomalies, because both failures share the same root cause (an inflated, conflated standard deviation).
- Day-of-week baselining costs sample size: with only 5 weeks of history, the day-of-week window has just 4 prior points, which is a thin standard deviation estimate. In practice you want at least 6-8 weeks of history before trusting this baseline, and you should still apply a minimum-history guard exactly as in a simpler per-entity outlier check.
- Other seasonality shapes (monthly billing cycles, holiday effects) need the equivalent treatment: partition by whatever unit of seasonality actually governs the metric, not just day-of-week by default.
Given a table touches(user_id, touch_id, channel varchar, occurred_at timestamp, is_conversion boolean), write ANSI SQL (or explain a set of queries) to compute per-channel revenue attribution using linear attribution for each conversion: split conversion credit equally across touchpoints within a conversion window. Describe performance considerations and how you would implement this model on very large datasets so it remains tractable.
Sample Answer
Direct answer
Linear attribution splits each conversion's value equally across every touchpoint that falls inside a bounded conversion window before it: find the conversion window for each converting user, count the touches inside it, and divide the conversion's revenue by that count. At scale, the two things that determine whether this stays fast are the join key (partition and cluster by user_id so a user's touches and conversion live together) and whether the window filter is applied before or after the count, since counting first and filtering second silently attributes revenue to touches outside the intended window.
Structured elaboration
Approach. Three steps, expressed as common table expressions (CTEs), which are standard American National Standards Institute (ANSI) SQL and portable across engines:
conversions: pull every row whereis_conversion = 1, giving each converting user's conversion timestamp and revenue.window_touches: join every non-conversion touch back to that user's conversion, keeping only touches whose elapsed time before the conversion falls inside a fixed conversion window (a business-defined parameter, 30 days below).touch_countsand the final aggregation: count touches per (user, conversion) pair, then for each surviving touch, creditrevenue / touch_countto its channel, and sum across all conversions grouped by channel.
Performance at scale. Three concerns dominate once the touches table is large:
- Join and partition strategy. The join between touches and conversions is keyed on
user_id; on a distributed warehouse (a columnar engine such as Snowflake, BigQuery, or Redshift), clustering or partitioning the physical table byuser_id(or a date-bucketeduser_id) keeps this join local to each partition instead of triggering a full shuffle across the cluster. - Window functions over self-joins where the engine supports it. The self-join pattern above is correct and portable, but on very large tables a window-function form (
COUNT(*) OVER (PARTITION BY user_id, conversion_id)computed directly on a pre-filtered, already-windowed row set) avoids materializing an intermediate join result twice, since the count and the later per-row division can share a single pass over the same partitioned data. This is a real optimization worth reaching for on a large warehouse table, described here as a design recommendation, not something separately benchmarked in this answer. - Filter before count, always. The date-window predicate must be applied inside the join that produces
window_touches, never as aHAVINGor post-aggregation filter; applying it too late would count touches outside the window intotouch_countswhile still excluding their revenue from the numerator, silently understating every channel's credit. The edge-case check in the Worked example below verifies this ordering is correct, not just assumed.
Worked example
Schema and pinned synthetic data (four users: a 3-touch conversion, a 1-touch conversion as a sanity check, a 5-touch conversion to make the equal-split arithmetic non-trivial, and a 3-touch user where two touches fall outside a 30-day conversion window and must be excluded), executed with Python's stdlib sqlite3:
CREATE TABLE touches (
user_id TEXT NOT NULL,
touch_id INTEGER NOT NULL,
channel TEXT NOT NULL,
occurred_at TIMESTAMP NOT NULL,
is_conversion INTEGER NOT NULL DEFAULT 0, -- 1 marks the conversion row itself
revenue DECIMAL(10,2) -- non-NULL only on the conversion row
);
INSERT INTO touches VALUES
-- user_1: 3-touch conversion, revenue $90 (each touch worth $30)
('user_1',1,'paid-search','2024-04-20 09:00:00',0,NULL),
('user_1',2,'email','2024-04-30 09:00:00',0,NULL),
('user_1',3,'organic-search','2024-05-05 09:00:00',0,NULL),
('user_1',4,'conversion','2024-05-10 09:00:00',1,90.00),
-- user_2: 1-touch conversion, sanity check, revenue $60
('user_2',1,'social','2024-05-09 09:00:00',0,NULL),
('user_2',2,'conversion','2024-05-10 09:00:00',1,60.00),
-- user_3: 5-touch conversion, revenue $250 (each touch worth $50); paid-search at touch 1 and touch 5
('user_3',1,'paid-search','2024-04-15 09:00:00',0,NULL),
('user_3',2,'social','2024-04-20 09:00:00',0,NULL),
('user_3',3,'display','2024-04-25 09:00:00',0,NULL),
('user_3',4,'email','2024-04-30 09:00:00',0,NULL),
('user_3',5,'paid-search','2024-05-08 09:00:00',0,NULL),
('user_3',6,'conversion','2024-05-10 09:00:00',1,250.00),
-- user_4: 3 raw touches, 2 outside the 30-day window (email, display), 1 inside (paid-search), revenue $120
('user_4',1,'email','2024-03-31 09:00:00',0,NULL),
('user_4',2,'display','2024-04-05 09:00:00',0,NULL),
('user_4',3,'paid-search','2024-04-25 09:00:00',0,NULL),
('user_4',4,'conversion','2024-05-10 09:00:00',1,120.00);
Linear attribution query (the date-difference expression below uses SQLite's julianday() so this exact query is directly runnable; on a production warehouse, swap only that expression for the engine's own day-difference function, DATEDIFF, date_diff, or interval subtraction, the surrounding ANSI SQL structure, CTEs, joins, and aggregation, is unchanged):
WITH conversions AS (
SELECT user_id, touch_id AS conversion_touch_id, occurred_at AS conversion_at, revenue
FROM touches
WHERE is_conversion = 1
),
window_touches AS (
SELECT t.user_id, c.conversion_touch_id, t.touch_id, t.channel, c.revenue
FROM touches t
JOIN conversions c
ON c.user_id = t.user_id
AND t.is_conversion = 0
AND julianday(c.conversion_at) - julianday(t.occurred_at) BETWEEN 0 AND 30
),
touch_counts AS (
SELECT user_id, conversion_touch_id, COUNT(*) AS n_touches
FROM window_touches
GROUP BY user_id, conversion_touch_id
)
SELECT wt.channel, ROUND(SUM(wt.revenue * 1.0 / tc.n_touches), 4) AS attributed_revenue
FROM window_touches wt
JOIN touch_counts tc ON tc.user_id = wt.user_id AND tc.conversion_touch_id = wt.conversion_touch_id
GROUP BY wt.channel
ORDER BY attributed_revenue DESC;
Output (actually executed with python3, sqlite3 stdlib module):
-- Linear attribution, per channel --
('paid-search', 250.0)
('social', 110.0)
('email', 80.0)
('display', 50.0)
('organic-search', 30.0)
sum(attributed_revenue) = 520.0
sum(conversion revenue) = 520.0
By hand: the $250 5-touch conversion splits into $50 per touch, and paid-search appears twice in that one path (touch 1 and touch 5), so it alone carries $100 of that conversion; added to $30 from the 3-touch conversion and $120 from the single in-window touch of the 30-day-filtered conversion, paid-search totals $250, matching the query exactly.
A second useful query: last-touch vs. linear, side by side, for the same conversions. Built by adding a ROW_NUMBER() OVER (PARTITION BY user_id, conversion_touch_id ORDER BY occurred_at DESC, touch_id DESC) ranking to the same window_touches CTE, taking rn = 1 as the last touch, and joining the two credit tables with a FULL OUTER JOIN on channel so a channel that only ever appears in one model still shows a 0 in the other rather than being silently dropped:
last_touch_rank AS (
SELECT wt.*, ROW_NUMBER() OVER (
PARTITION BY wt.user_id, wt.conversion_touch_id
ORDER BY wt.occurred_at DESC, wt.touch_id DESC
) AS rn
FROM window_touches wt
),
last_touch_credit AS (
SELECT channel, SUM(revenue) AS last_touch_revenue
FROM last_touch_rank WHERE rn = 1 GROUP BY channel
)
SELECT COALESCE(l.channel, lt.channel) AS channel,
ROUND(COALESCE(l.linear_revenue, 0), 4) AS linear_revenue,
ROUND(COALESCE(lt.last_touch_revenue, 0), 4) AS last_touch_revenue
FROM linear_credit l
FULL OUTER JOIN last_touch_credit lt ON lt.channel = l.channel
ORDER BY channel;
Output (actually executed):
('display', 50.0, 0.0)
('email', 80.0, 0.0)
('organic-search', 30.0, 90.0)
('paid-search', 250.0, 370.0)
('social', 110.0, 60.0)
sum(linear_revenue) = 520.0
sum(last_touch_revenue) = 520.0
total conversion revenue = 520.0
Both columns independently sum to the full $520 of conversion revenue, since each model fully partitions every conversion on its own; they simply disagree about WHICH channel gets the credit. display and email never happen to be a last touch across these four conversions, so they read $0 under last-touch despite earning real linear credit, a concrete illustration of why the two models can tell very different stories about the same underlying data.
Complexity
- The core query is one join (
touchestoconversions, both filtered), oneGROUP BYfor counts, and one more aggregation: O(T) where T is the number of touch rows within the conversion window, assuming the join uses an index or a partition-local hash join onuser_idrather than a full cross-table scan. - The window-function form (
ROW_NUMBER() OVER (...)) used for the last-touch comparison adds a sort within each(user_id, conversion_touch_id)partition; on a columnar warehouse this is typically implemented as a partitioned sort, O(Tlogk) where k is the average touches per conversion, which is small (single digits to low tens) even when T is enormous, so this stays cheap in practice. - Space: the intermediate
window_touchesCTE materializes at most one row per (touch, conversion) pair inside the window, bounded by T, not by the full unfiltered touch table, provided the window predicate is pushed into the join as shown rather than applied afterward.
Edge cases
- Single-touch conversion (
user_2above): linear and last-touch degenerate to the same answer, verified directly and in isolation:[('social', 1, 60.0)], one touch, full $60 credited, which both models must agree on by construction. - Conversion window filter must actually exclude stale touches, not just compile.
user_4has three raw touches but only one within 30 days of its conversion; verified directly:all raw touches for user_4: [(1, 'email', ...), (2, 'display', ...), (3, 'paid-search', ...)]versustouches surviving the 30-day window filter: [(3, 'paid-search')], confirming exactly two of three were correctly excluded. - The same channel appearing more than once in one conversion path (
user_3's twopaid-searchtouches): each occurrence is still one of the five equally-weighted touches, so the channel's total credit for that conversion is 2×5250=$100, not capped at a single share; this is a deliberate property of linear attribution, not a bug. - A user with touches but no conversion never enters
conversionsat all, so none of their touches are ever counted or attributed, correctly excluding non-converting activity from revenue attribution entirely. - NULL
revenueonly ever appears on non-conversion rows in this schema; the query never readsrevenuefrom a non-conversion row, so aNULLthere is inert by construction rather than something the query needs to guard against separately.
Trade-offs and pitfalls
- Linear attribution assumes every touchpoint contributed equally, which is rarely true. A touch two minutes before conversion and a touch three weeks before conversion get identical credit here; a time-decay or position-based model (more credit to first and last touch, as one common alternative) captures that intuition, linear does not, and that is a modeling choice to make explicitly, not an oversight to fix inside this query.
- Common mistake: filtering the conversion window after computing
touch_countsinstead of before. Doing the filter late would count out-of-window touches into the denominator while still excluding their revenue share from ever being attributed, quietly shrinking every in-window touch's credit for no principled reason; the CTE order above avoids this specifically by filtering insidewindow_touches, the very first step. - Common mistake: assuming every conversion has at least one touch. If instrumentation gaps mean some conversions genuinely have zero touches in the window, that conversion's revenue is silently excluded from
sum(attributed_revenue), which is why validating that the attributed total equals the true conversion-revenue total (done explicitly above) is not optional, it is the only way to catch this kind of silent data loss. FULL OUTER JOINsupport is not universal. It rendered correctly in this environment's SQLite build, but some engines and older SQLite builds do not support it directly; the portable fallback is aUNIONof twoLEFT JOINs (one anchored on each side), which produces the identical result set and is worth knowing as the fallback pattern rather than assumingFULL OUTER JOINis always available.
Write an optimized SQL query using window functions to compute a rolling 90-day average revenue per user (ARPU) partitioned by region, handling days with no purchases and avoiding double-counting users who purchase multiple times in a day. Explain the indexes and performance tuning you would use for large datasets.
Sample Answer
Direct answer
Compute a rolling 90-day ARPU (average revenue per user) per region using a window function over daily aggregated purchases, being careful to count each user once per day even if they made multiple purchases that day, and to index/partition the underlying table so the rolling window doesn't force a full scan on every row.
Structured elaboration
- Avoiding double-counting same-day purchases: aggregate to one row per (user, day, region) first (summing that day's purchases), THEN apply the rolling window over days, rather than letting a naive per-transaction window silently weight active repeat-purchasers more heavily in the denominator than the numerator.
- The rolling window:
SUM(daily_revenue) OVER (PARTITION BY region ORDER BY day ROWS BETWEEN 89 PRECEDING AND CURRENT ROW) / (rolling distinct active users over the same 90-day window). The distinct-user denominator over a rolling window is the more expensive half of this computation (a plainSUMover a frame is cheap; a rolling DISTINCT COUNT is not natively supported as a window aggregate in most engines and typically needs a separate approach -- in rough order of how often each is reached for in practice: a pre-aggregated daily distinct-user table combined with careful merge logic is usually the first thing to try; a self-join works for smaller data volumes but degrades quickly as the table grows; a full approximate-distinct sketch is worth its added complexity mainly once the table is too large for either of the other two to stay cheap). - Indexing and partitioning for large datasets: partition or cluster the physical table by
regionanddayso the engine can prune to the relevant date range and region without scanning unrelated partitions -- note this is a different sense of "partition" from thePARTITION BY regionwindow-function clause used above: that clause tells the SQL engine how to group rows for computation, while this one is about how the table's data is physically laid out on disk before any query runs. A covering index on(region, day, user_id)supports both the daily aggregation step and the rolling-window step without needing to revisit the raw transaction table -- "covering" means the index already contains every column the query touches (region, day, user_id), so the engine can answer entirely from the index without jumping back to the base table's rows.
Worked example
Recall the definition of average revenue per user (ARPU) as total billed revenue over active subscriber count for a period: a single-month calculation computes that once for one fixed calendar month, while this version recomputes it for a 90-day window ENDING on every day, partitioned by region:
WITH daily AS (
SELECT region, purchase_date AS day, user_id, SUM(amount) AS user_daily_amount
FROM purchases
GROUP BY region, purchase_date, user_id
)
SELECT region, day,
SUM(user_daily_amount) OVER w AS rolling_90d_revenue,
-- distinct active users over the rolling window needs a dedicated
-- mechanism (approximate sketch or a maintained rolling-distinct table);
-- shown here as a placeholder for that piece
rolling_90d_distinct_users,
ROUND(SUM(user_daily_amount) OVER w / NULLIF(rolling_90d_distinct_users, 0), 2) AS rolling_arpu
FROM daily
WINDOW w AS (PARTITION BY region ORDER BY day ROWS BETWEEN 89 PRECEDING AND CURRENT ROW);
The key correctness point demonstrated by the daily common table expression: a user who made three separate $50 purchases in one day contributes $150 to the numerator but must still only count as ONE active user that day in the denominator; grouping to (region, day, user_id) before the rolling window is what guarantees that.
Trade-offs & pitfalls
- The distinct-user denominator over a rolling window is the real engineering problem here, not the revenue numerator: a plain
SUMover a frame is a cheap, well-supported window operation; a rolling 90-day DISTINCT COUNT is not, and reaching for an approximate-distinct sketch such as HyperLogLog (a compact, fixed-size probabilistic data structure that estimates the number of distinct values in a set within a small, well-characterized error, and that can be merged across time buckets without re-touching the original raw rows) is often the pragmatic answer once the table is large. - Index/partition choice depends on query pattern: if most queries filter to a single region and a recent date range, partition by region first and cluster by day within it; if queries instead scan all regions for a fixed recent window, cluster primarily by day.
- A day with zero purchases in some region should still appear in the series with revenue 0, or a rolling average silently and incorrectly skips gaps; generate the full calendar range explicitly rather than relying only on the rows that happen to exist.
Unlock Full Question Bank
Get access to all 23 Advanced SQL: Metric Monitoring, Anomaly Detection, and Data Correctness at Scale interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.