Analyzing Noisy A/B Experiment Metrics and SRM in SQL
SQL & DataModel answerLast updated
Write SQL queries to censor crossover exposures, compute 14-day conversion metrics under blackout constraints, and calculate an SRM chi-square p-value.
You are analyzing an A/B testing experiment (experiment_id = 'tracker_vlaunch_v1'). The target evaluation date is 2025-09-01.
Data Schema
users
user_id(INT)country(TEXT)signup_date(DATE)marketing_channel(TEXT)
exposures
user_id(INT)experiment_id(TEXT)variant(TEXT)exposure_ts(TIMESTAMP)source(TEXT)
sessions
user_id(INT)session_start(TIMESTAMP)device(TEXT)is_bot(BOOLEAN)
orders
order_id(INT)user_id(INT)order_ts(TIMESTAMP)revenue(NUMERIC(10,2))refunded(BOOLEAN)
Tasks
Task A: Core Metrics Calculation
Write a single PostgreSQL query for exposures logged between 2025-08-01 and 2025-08-24 (inclusive of the entire day of August 24) for experiment_id = 'tracker_vlaunch_v1'.
Requirements and Business Rules:
- Exposure & Crossover Attribution: Assign each user strictly to their earliest exposure variant ever recorded for this experiment. Any subsequent exposures to a different variant (crossovers) must be ignored (censored).
- Bot Filtering & Qualification: A user is considered qualified if they have at least one non-bot session (
is_bot = false) occurring on or prior to their earliest exposure timestamp (session_start <= exposure_ts). The device used during their earliest qualified session is designated as their qualifying device. - Cohort Scope: Filter the output to include only users residing in
USorCA. - Time Window & Blackout Exclusions:
- Track orders occurring on or after the user's earliest exposure timestamp, strictly within a 14-day window (
order_ts < exposure_ts + INTERVAL '14 days'), and strictly prior to2025-09-01. - Exclude any orders placed during an iOS system blackout period defined as
['2025-08-10 00:00:00', '2025-08-12 00:00:00')if the user's qualifying device wasios.
- Track orders occurring on or after the user's earliest exposure timestamp, strictly within a 14-day window (
- Output Schema: Group by
variantandcountryand return:variantcountryusers_exposed: Total count of exposed users in this country.qualified_users: Total count of qualified non-bot users.converters_14d: Count of qualified users who placed at least one eligible order in the 14-day window.conv_rate_14d:converters_14d / qualified_users(rounded to 4 decimal places).revenue_14d: Total revenue from non-refunded eligible orders placed by qualified users in the window.refund_rate_14d: Total refunded eligible orders divided by total eligible orders placed by qualified users in the window (rounded to 4 decimal places).
Task B: Sample Ratio Mismatch (SRM) Test
Write a second SQL query to perform a 50/50 Chi-Square Goodness-of-Fit test for Sample Ratio Mismatch (SRM) on qualified users across control and B variants.
Requirements:
- Calculate
observed_count_control,observed_count_B,expected_each,chi2_stat, andp_value. - Use an accurate approximation for the chi-square CDF/p-value (such as the Abramowitz & Stegun approximation for the error function) using standard mathematical functions (
EXP,POWER,LN,SQRT) without external extensions or custom UDFs.
Hints
Hint 1
Find each user's absolute earliest exposure timestamp across the whole table before filtering by the launch date range; otherwise, cross-over users exposed earlier in July might be wrongly counted as first exposed in August.
Hint 2
Aggregate orders per user first before rolling up to the variant-country level to ensure user-level conversion metrics are distinct.
Hint 3
For the 1-DOF chi-square p-value, recall that chi2 with 1 degree of freedom relates to the standard normal distribution via Z = sqrt(chi2), making p = erfc(Z / sqrt(2)).
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Technical Solution & Strategy
Task A Pipeline Strategy
- Global First Exposure Attribution:
- Apply
DISTINCT ON (user_id)ordered byexposure_tsover the entireexposurestable fortracker_vlaunch_v1. - Crucial Rule: Do not filter by the
2025-08-01to2025-08-24date range prior to finding the minimum timestamp. Filtering first could re-attribute a user exposed in late July to a different variant seen in August.
- Apply
- Device & Qualification Check:
- Join
sessionswhereis_bot = falseandsession_start <= exposure_ts. - Use
DISTINCT ON (user_id)ordered bysession_start ASCto identify the user's earliest qualifying session and tag theirqualifying_device.
- Join
- Cohort Aggregation & Order Attribution:
- Restrict to users in
USorCA. - Join
ordersmatching:order_ts >= exposure_tsorder_ts < exposure_ts + INTERVAL '14 days'order_ts < '2025-09-01'- Exclusion:
NOT (qualifying_device = 'ios' AND order_ts >= '2025-08-10' AND order_ts < '2025-08-12')
- Aggregate orders to the user level first to ensure accurate converter counts and revenue calculations.
- Restrict to users in
Task A Query
WITH first_exposure AS (
-- Step 1: Assign immutable initial exposure and censor later variant crossovers
SELECT DISTINCT ON (user_id)
user_id,
variant,
exposure_ts
FROM exposures
WHERE experiment_id = 'tracker_vlaunch_v1'
ORDER BY user_id, exposure_ts ASC
),
qualified_users AS (
-- Step 2: Determine qualification status and qualifying device
SELECT DISTINCT ON (fe.user_id)
fe.user_id,
fe.variant,
fe.exposure_ts,
s.device AS qual_device
FROM first_exposure fe
JOIN sessions s
ON fe.user_id = s.user_id
AND s.is_bot = FALSE
AND s.session_start <= fe.exposure_ts
WHERE fe.exposure_ts >= '2025-08-01 00:00:00'
AND fe.exposure_ts < '2025-08-25 00:00:00'
ORDER BY fe.user_id, s.session_start ASC
),
analysis_cohort AS (
-- Step 3: Combine all exposed users in target countries with qualification status
SELECT
fe.user_id,
fe.variant,
u.country,
qu.qual_device,
(qu.user_id IS NOT NULL) AS is_qualified,
fe.exposure_ts
FROM first_exposure fe
JOIN users u ON fe.user_id = u.user_id
LEFT JOIN qualified_users qu ON fe.user_id = qu.user_id
WHERE fe.exposure_ts >= '2025-08-01 00:00:00'
AND fe.exposure_ts < '2025-08-25 00:00:00'
AND u.country IN ('US', 'CA')
),
user_orders AS (
-- Step 4: Attribute qualifying orders windowed per user
SELECT
ac.user_id,
COUNT(*) AS total_orders,
COUNT(*) FILTER (WHERE o.refunded = TRUE) AS refunded_orders,
SUM(CASE WHEN o.refunded = FALSE THEN o.revenue ELSE 0 END) AS valid_revenue
FROM analysis_cohort ac
JOIN orders o ON ac.user_id = o.user_id
WHERE ac.is_qualified = TRUE
AND o.order_ts >= ac.exposure_ts
AND o.order_ts < ac.exposure_ts + INTERVAL '14 days'
AND o.order_ts < TIMESTAMP '2025-09-01 00:00:00'
AND NOT (
ac.qual_device = 'ios'
AND o.order_ts >= TIMESTAMP '2025-08-10 00:00:00'
AND o.order_ts < TIMESTAMP '2025-08-12 00:00:00'
)
GROUP BY ac.user_id
)
-- Step 5: Metric rollup by variant and country
SELECT
ac.variant,
ac.country,
COUNT(*) AS users_exposed,
COUNT(*) FILTER (WHERE ac.is_qualified) AS qualified_users,
COUNT(uo.user_id) AS converters_14d,
ROUND(
COUNT(uo.user_id)::NUMERIC / NULLIF(COUNT(*) FILTER (WHERE ac.is_qualified), 0),
4
) AS conv_rate_14d,
COALESCE(SUM(uo.valid_revenue), 0) AS revenue_14d,
ROUND(
SUM(uo.refunded_orders)::NUMERIC / NULLIF(SUM(uo.total_orders), 0),
4
) AS refund_rate_14d
FROM analysis_cohort ac
LEFT JOIN user_orders uo ON ac.user_id = uo.user_id
GROUP BY ac.variant, ac.country
ORDER BY ac.variant, ac.country;
Task B: SRM Chi-Square Test
For $k = 2$ variants under a 50/50 expected split, the Chi-Square statistic with 1 degree of freedom is:
$$\chi^2 = \frac{(O_{\text{control}} - E)^2}{E} + \frac{(O_B - E)^2}{E}$$
Where $E = \frac{O_{\text{control}} + O_B}{2}$.
For $1 \text{ d.o.f.}$, the $p$-value is equivalent to $2 \cdot (1 - \Phi(\sqrt{\chi^2})) = \text{erfc}\left(\frac{\sqrt{\chi^2}}{\sqrt{2}}\right)$.
Using Abramowitz & Stegun approximation (formula 7.1.26): $$x = \frac{\sqrt{\chi^2}}{\sqrt{2}}$$ $$t = \frac{1}{1 + p \cdot x}, \quad \text{where } p = 0.3275911$$ $$\text{erfc}(x) \approx (a_1 t + a_2 t^2 + a_3 t^3 + a_4 t^4 + a_5 t^5) e^{-x^2}$$
WITH first_exposure AS (
SELECT DISTINCT ON (user_id)
user_id,
variant,
exposure_ts
FROM exposures
WHERE experiment_id = 'tracker_vlaunch_v1'
ORDER BY user_id, exposure_ts ASC
),
qualified_cohort AS (
SELECT
fe.user_id,
fe.variant
FROM first_exposure fe
WHERE fe.exposure_ts >= '2025-08-01 00:00:00'
AND fe.exposure_ts < '2025-08-25 00:00:00'
AND fe.variant IN ('control', 'B')
AND EXISTS (
SELECT 1 FROM sessions s
WHERE s.user_id = fe.user_id
AND s.is_bot = FALSE
AND s.session_start <= fe.exposure_ts
)
),
counts AS (
SELECT
COUNT(*) FILTER (WHERE variant = 'control') AS obs_control,
COUNT(*) FILTER (WHERE variant = 'B') AS obs_b
FROM qualified_cohort
),
stats AS (
SELECT
obs_control,
obs_b,
(obs_control + obs_b) / 2.0 AS expected_each,
(
POWER(obs_control - ((obs_control + obs_b) / 2.0), 2) / NULLIF((obs_control + obs_b) / 2.0, 0) +
POWER(obs_b - ((obs_control + obs_b) / 2.0), 2) / NULLIF((obs_control + obs_b) / 2.0, 0)
) AS chi2_stat
FROM counts
),
z_calc AS (
SELECT
obs_control,
obs_b,
expected_each,
chi2_stat,
SQRT(chi2_stat) / SQRT(2.0) AS x
FROM stats
),
erfc_calc AS (
SELECT
obs_control,
obs_b,
expected_each,
chi2_stat,
(1.0 / (1.0 + 0.3275911 * x)) AS t,
EXP(-POWER(x, 2)) AS exp_term
FROM z_calc
)
SELECT
obs_control AS observed_count_control,
obs_b AS observed_count_B,
expected_each,
ROUND(chi2_stat::NUMERIC, 4) AS chi2_stat,
ROUND(
(
t * (0.254829592 +
t * (-0.284496736 +
t * (1.421413741 +
t * (-1.453152027 +
t * 1.061405429)))) * exp_term
)::NUMERIC,
6
) AS p_value
FROM erfc_calc;
Key Takeaways & Common Pitfalls
- Pre-filtering Exposures: Filtering exposures by date before taking the min exposure timestamp risks attributing cross-over users to wrong variants if their first exposure happened prior to the filter start date.
- Fan-out on Joins: Always aggregate downstream tables (
orders) before aggregating at the cohort level (variant, country), otherwise duplicate order rows will artificially multiplyqualified_userscounts. - Denominator Alignment:
conv_rate_14ddivides converters byqualified_users(notusers_exposed).refund_rate_14ddivides refunded orders by total orders in the window.