Databases & SQL Master Course — 185. Experiment Metric Preparation
Lesson 185 Experiment Metric Preparation
Prerequisites and objectives
Complete Lesson 184 and review the earlier concepts named in this lesson. You will prepare one row per assigned fictional user, preserve zero-outcome assignments, flag missing exposure, and reject duplicate assignment identities. Review join conditions and aggregation. This lesson builds a descriptive analysis input; it does not establish randomization, statistical significance, or a treatment effect.
Separate assignment, exposure, and outcome
Assignment records the intended analysis group. Exposure records whether a user received a qualifying presentation. Outcome records observed events in the accepted window. These are different relations and should not be collapsed merely because they share user identity. Their differences are often the most important diagnostic evidence.
The lab has four assigned users, two in each arm. Every assignment begins at minute zero, and the complete outcome window ends at minute ten, excluded. Only users one and three have recorded exposure. User two has an outcome despite missing exposure, and an unassigned user five has an outcome that needs investigation.
The preparation contract includes every assigned user and sums accepted post-assignment outcome cents. Missing qualifying outcomes become zero only because this fictional window is declared complete. In real telemetry, absence may mean missing ingestion rather than no activity; completeness evidence must support the zero interpretation.
CREATE TABLE lab_assign185(user_id INTEGER PRIMARY KEY,arm TEXT NOT NULL CHECK(arm IN ('A','B')),assigned_min INTEGER NOT NULL);
CREATE TABLE lab_expose185(id INTEGER PRIMARY KEY,user_id INTEGER NOT NULL,minute INTEGER NOT NULL);
CREATE TABLE lab_outcome185(id INTEGER PRIMARY KEY,user_id INTEGER NOT NULL,minute INTEGER NOT NULL,cents INTEGER NOT NULL CHECK(cents>=0));
INSERT INTO lab_assign185 VALUES(1,'A',0),(2,'A',0),(3,'B',0),(4,'B',0);
INSERT INTO lab_expose185 VALUES(1,1,1),(2,3,1);
INSERT INTO lab_outcome185 VALUES(1,1,5,5),(2,1,6,7),(3,2,8,8),(4,3,-1,20),(5,3,5,10),(6,5,5,99);
CREATE VIEW lab_analysis185 AS SELECT a.user_id,a.arm,COALESCE(SUM(o.cents),0) AS cents,EXISTS(SELECT 1 FROM lab_expose185 e WHERE e.user_id=a.user_id AND e.minute>=a.assigned_min AND e.minute<10) AS exposed FROM lab_assign185 a LEFT JOIN lab_outcome185 o ON o.user_id=a.user_id AND o.minute>=a.assigned_min AND o.minute<10 GROUP BY a.user_id,a.arm ORDER BY a.user_id;
| User and arm | Accepted outcome | Exposure flag |
|---|---|---|
| 1 / A | 12 | 1 |
| 2 / A | 8 | 0 |
| 3 / B | 10 | 1 |
| 4 / B | 0 | 0 |
Build one row per assignment before comparing arms
The assignment relation anchors the left join. Outcome conditions belong in the join predicate so a user without accepted outcomes remains present. Placing a required outcome condition in WHERE can turn preservation into exclusion and change the denominator. Grouping then reduces several legitimate outcome events to one assigned-user total.
The setup exposes the preparation query as an ordinary view for repeatable inspection. Exposure is represented with EXISTS rather than a raw join that could multiply outcomes when a user is exposed repeatedly. A binary exposure flag answers whether any qualifying exposure exists. If exposure timing, dose, or repeated presentations matter, retain a separate well-defined measure instead of letting join multiplicity stand in for one.
This preparation resembles an assignment-based analysis population, but the SQL cannot prove that assignments were randomized or correctly delivered. Keep allocation procedure, eligibility, exclusions, and measurement design as separate reviewed evidence. A balanced count of two users per arm is not a randomization test.
Exercise 1
Create the assignment-anchored analysis rows.
Worked solution
-- Connection A
SELECT user_id,arm,cents,exposed FROM lab_analysis185 ORDER BY user_id;
User one’s two accepted events sum to twelve. User three’s pre-assignment event is excluded, leaving ten. User four remains with zero outcome and no exposure. User five is not silently assigned to an arm merely because an outcome exists.
Exercise 2
Compute descriptive arm totals without dropping unexposed assignments.
Worked solution
-- Connection A
WITH p AS (SELECT user_id,arm,cents,exposed FROM lab_analysis185 ORDER BY user_id) SELECT arm,COUNT(*),SUM(cents),AVG(cents) FROM p GROUP BY arm ORDER BY arm;
Each denominator is two assignments. The means are ten and five fictional cents per assigned user. These tiny descriptive differences do not establish a causal effect or statistical reliability. The query’s purpose is to make the population and arithmetic inspectable.
Exercise 3
Report exposure gaps and unmatched outcome identities.
Worked solution
-- Connection A
WITH p AS (SELECT user_id,arm,cents,exposed FROM lab_analysis185 ORDER BY user_id) SELECT arm,SUM(CASE WHEN exposed=0 THEN 1 ELSE 0 END) FROM p GROUP BY arm ORDER BY arm;
SELECT DISTINCT o.user_id FROM lab_outcome185 o WHERE NOT EXISTS (SELECT 1 FROM lab_assign185 a WHERE a.user_id=o.user_id) ORDER BY o.user_id;
Each arm has one assignment without recorded exposure, and user five has no assignment. These are separate diagnostics. Automatically deleting them would change the analysis population or hide a pipeline issue; investigate against the declared collection and eligibility rules.
Exercise 4
Contrast an exposure-only denominator and reject duplicate assignment.
Worked solution
-- Connection A
WITH p AS (SELECT user_id,arm,cents,exposed FROM lab_analysis185 ORDER BY user_id) SELECT arm,COUNT(*),AVG(cents) FROM p WHERE exposed=1 GROUP BY arm ORDER BY arm;
INSERT INTO lab_assign185 VALUES(1,'B',0);
SELECT COUNT(*) FROM lab_assign185;
The exposure-only means differ because the population changed to one user per arm. That is a different analysis choice, not an automatic improvement. The primary key rejects assigning user one a second row; crossovers and reassignments would require an explicit versioned design rather than silent replacement.
Validate data before interpreting differences
Check assignment uniqueness, arm labels, eligibility dates, observation completeness, duplicate source event identities, and events preceding assignment. Distinguish multiple genuine purchases from duplicated delivery of the same event. A row identifier generated at ingestion does not by itself prove an upstream event was received only once.
Exposure logging can fail differently across arms or devices. Conditioning on observed exposure may select different kinds of users and change the question being estimated. Report the descriptive gap and consult the experiment’s prespecified analysis plan rather than choosing the denominator that gives the preferred result.
Keep the observation cutoff consistent across users or define a fixed follow-up duration with a maturity requirement. A user assigned just before a report runs should not be compared with one observed for a full week under an unlabeled mixture. This fixture avoids that issue by sharing assignment time and a complete fixed window.
A useful handoff includes the exact user-grain dataset, variable definitions, source snapshot, cutoff, exclusion rules, missingness diagnostics, and aggregate reconciliation. Statistical analysis can then evaluate the design and uncertainty without reverse-engineering a SQL notebook. Do not put sensitive real-user identifiers in a public example or portfolio.
Pitfalls and summary
Anchor the chosen population, aggregate outcomes before combining independent event streams, and keep exposure diagnostics visible. Preserve zero-outcome assignments only under a justified completeness contract. SQL can prepare a trustworthy dataset while leaving randomization quality, causal interpretation, and uncertainty explicitly unresolved.
Knowledge check
Question 1
Why does user four remain in the prepared dataset?
- The query restricts membership to users with recorded exposure
- Assignment anchors the population despite no qualifying outcome
- An inner join automatically creates a zero row
- The aggregation adds an extra row to balance the arm counts
Answer and explanation
B. The left join preserves assigned users; zero relies on the stated complete-window contract.
Question 2
Why use EXISTS for the exposure flag?
- EXISTS replaces the need to aggregate multiple outcome events
- A raw exposure join guarantees one row per assignment
- Repeated exposure rows should not multiply outcome amounts
- Exposure events and purchase events always have identical grain
Answer and explanation
C. The flag is a membership test, separate from outcome aggregation.
Question 3
Why is user three’s twenty-cent event excluded?
- It belongs to arm B, which is excluded from totals
- Only the smallest event amount is counted
- Every user can have only one outcome event
- It occurred before assignment
Answer and explanation
D. The accepted window begins at the user’s assignment time.
Question 4
What changes in the exposure-only comparison?
- The analysis population and its denominator
- Only the display formatting of the same estimate
- The original assignment randomization is newly proven
- The outcome window changes from post-assignment to lifetime totals
Answer and explanation
A. Conditioning on exposure answers a different population question.
Question 5
What can the observed arm means establish here?
- A statistically significant treatment effect
- Proof that assignment was random
- Proof that missing exposure cannot bias interpretation
- Descriptive arithmetic under the stated fixture and definitions
Answer and explanation
D. Data preparation does not establish experimental design or causal uncertainty.
Execution scope
These scenarios were executed with SQLite 3.53.1 using separate connections to newly created disposable local database files. No existing or external database was used. Each scenario starts from a fresh fixture. Python was an internal verification harness, not a learner prerequisite. Follow the labeled connection order in SQL clients that open the same disposable file.
Primary references
- SELECT and LEFT JOIN: Population anchoring and predicate placement.
- Aggregate functions: User totals and descriptive means.
- EXISTS: Exposure membership without fan-out.
- Primary keys: Unique assignment identity.