The SQL behind an A/B test: Writing experiment queries in Snowflake

A Snowflake A/B test query is only trustworthy when its rows preserve the experiment's random assignment.
Calculating the average outcome for control and treatment is easy. Building the correct denominator is harder. A plausible result can still include outcomes before exposure, count events instead of randomized users, mix staging with production, drop non-converters, or compare a mature control window with an immature treatment window.
This guide builds the SQL in layers: first exposure, exposure-quality checks, post-exposure outcomes, one value per randomization unit, variation summaries, and operational QA. It also explains which work belongs in Snowflake and which work is safer in a tested statistical engine.
The examples assume user-level randomization and completed-order revenue. Replace database, schema, table, timestamp, environment, and business-status values before running them. Use a development role and bounded dates first.
Define the analytical contract
Assume these tables.
ANALYTICS.EXPERIMENT_EXPOSURES contains:
EXPERIMENT_ID VARCHARUSER_ID VARCHARVARIATION_ID VARCHAREXPOSED_AT TIMESTAMP_TZENVIRONMENT VARCHAR
ANALYTICS.ORDERS contains:
ORDER_ID VARCHARUSER_ID VARCHARORDER_AT TIMESTAMP_TZNET_REVENUE NUMBER(18,2)ORDER_STATUS VARCHAR
An exposure means the user had a real opportunity to experience the assigned variation. A background flag refresh or an eligibility lookup is not necessarily exposure. Write this semantic rule beside the schema.
The analysis unit must match assignment. If accounts are randomized, use ACCOUNT_ID and aggregate all user events to one account value. Foreign-key joins do not make user rows statistically independent inside an assigned account.
Use half-open intervals: >= start and < end. They compose without overlap when a scheduled job advances from one analysis window to the next.
Select the first exposure and identify crossovers
This query keeps repeated exposure rows for diagnostics, counts distinct variations per user, selects the earliest qualifying exposure, and excludes users observed in both groups.
Snowflake evaluates QUALIFY after window functions, so the query can filter ROW_NUMBER() without another nested select. The variation key breaks identical-timestamp ties deterministically; identical cross-variation timestamps should still trigger investigation.
Do not discard the crossover measure after filtering. It is an operational signal for unstable identity, non-sticky assignment, delayed configuration, environment overlap, or duplicated pipelines.
Create one post-exposure value per user
Extend the same CTEs with the following unit-value and variation-summary steps. The broad order bounds improve pruning; user-specific predicates enforce the fourteen-day conversion window.
The LEFT JOIN retains users with zero completed orders. Keep order filters inside the join. A final WHERE o.order_status = 'completed' would remove null matches, turn the analysis into a converter-only comparison, and inflate the metric.
Aggregating to unit_values before the variation summary protects the experimental sample size. Revenue events are not independently randomized; users are. VAR_SAMP returns the dispersion of user-level revenue that a statistical engine needs.
The query uses Snowflake's 0 to express the outcome window relative to each user's first exposure. Keep that per-user rule even when a broad literal predicate is added for pruning.
The summary is not a complete significance test. SQL is well suited to population construction and sufficient statistics. A tested statistical layer should handle confidence intervals or Bayesian posteriors, sequential monitoring, variance reduction, and multiple comparisons. A public discussion about warehouse-native A/B test analysis illustrates both the transparency of this approach and the platform work needed around the SQL.
Put Snowflake metrics to work
Connect governed exposures and outcomes to transparent experiment analysis without rebuilding the statistical workflow for every test.
Start Building FreeCalculate descriptive lift for reconciliation
Use a pivot only after the variation summaries are correct. This helps compare an experimentation UI with analyst-owned SQL.
Return NULL when the control mean is zero instead of manufacturing a relative percentage. Always preserve absolute differences in the original unit: percentage points for conversion and currency per randomized unit for revenue.
Observed lift alone does not answer whether to ship. Define the smallest practically useful effect before launch, then interpret uncertainty and guardrails against that threshold.
Run quality checks before interpreting effects
Sample ratio mismatch
For a nominal 50/50 allocation, calculate the Pearson chi-square statistic from eligible counts. Use a statistics library or experimentation platform for the p-value and alert policy.
A failed sample ratio mismatch check means the observed variation counts do not match allocation closely enough for the configured threshold. It does not identify the cause. Check targeting, assignment, exposure emission, warehouse ingestion, filters, joins, and missing IDs.
Crossover rate
Repeated evaluation in one variation can be normal. A unit seen in two variations has ambiguous treatment. Report and investigate it even when the main query excludes it.
Fact-table grain
If the order fact promises one row per order, test the promise.
An empty result passes. If the source stores order versions, create a model that selects the current valid row using explicit effective-time logic. Do not add DISTINCT to the experiment query and hide uncertainty about grain.
Pre-exposure outcome leakage
Prior orders are valid inputs for pre-experiment covariates or eligibility. They are not post-treatment revenue. Separating these windows is essential when applying CUPED.
Handle metric maturity and late-arriving facts
A user exposed yesterday has not completed a fourteen-day outcome window. Either include only mature users or use a cumulative method that compares equal follow-up across variations.
For a mature-cohort analysis, add:
Use an as_of time that reflects source completeness, not merely CURRENT_TIMESTAMP(). Subscription renewals, refunds, offline events, and batch ingestion can update old periods. Publish a metric-lag policy and re-run historical windows when late data is expected.
Time zones need equal care. Store instant timestamps consistently, then derive business dates in an explicit zone. A revenue day based on an account locale may not align with an exposure day in UTC. Implicit session time zones make results difficult to reproduce.
Identity models must be effective-dated. Joining historical exposures to the current anonymous-to-authenticated identity map can rewrite past unit membership. Freeze or reconstruct the mapping as it was known for the analysis contract.
Make Snowflake experiment queries efficient
Snowflake automatically stores table data in micro-partitions and can prune them when predicates align with useful metadata. The micro-partition and clustering documentation explains why bounded time filters and natural clustering matter on large event tables.
Apply these practices:
- select only necessary columns;
- use literal or clearly bound time ranges around every large fact;
- aggregate raw events to reusable unit-level facts;
- avoid repeatedly scanning the same exposure and identity transformations;
- use a dedicated, auto-suspending analysis warehouse;
- size up only when reduced runtime offsets higher credit consumption;
- schedule broad refreshes away from interactive workloads;
- set a query tag for attribution.
Set the tag before an analysis session or in the service connection:
Snowflake Query History can filter by user, warehouse, query tag, duration, and query hash. SNOWFLAKE.ACCOUNT_USAGE.QUERY_HISTORY provides longer-lived metadata such as bytes scanned, queue time, errors, warehouse size, and query tag.
Use a dedicated warehouse and attach a resource monitor with notifications and suspension thresholds. Resource monitors cover user-managed warehouses, not every serverless service, so pair them with broader budgets where necessary.
Connect the query model to GrowthBook
SQL alone can produce an audit result. An experimentation program also needs reusable metrics, diagnostics, permissions, statistical methods, result history, and decision workflows.
GrowthBook's warehouse-native architecture queries Snowflake data and exposes generated SQL. Configure:
- a dedicated Snowflake user, role, and analysis warehouse;
- an experiment-assignment query equivalent to the first-exposure population;
- a reusable fact table with unit, timestamp, and value columns;
- metric definitions for conversion and revenue;
- conversion windows, caps, covariates, guardrails, and statistical settings;
- an A/A test and a completed A/B reconciliation.
Preview the generated SQL. Compare eligible units, crossovers, mature units, sums, means, and variances with the reference. If they differ, resolve the data contract before comparing p-values or credible intervals.
GrowthBook can then reuse those governed metrics across experiment analysis and warehouse-native product analytics, reducing drift between dashboards and decisions.
Production checklist
Before a Snowflake result informs a release decision, confirm:
- exposure represents an opportunity to receive treatment;
- the randomization unit matches the metric grain;
- first exposure is deterministic;
- crossovers are measured and handled consistently;
- environment and eligibility filters are explicit;
- primary outcomes occur after exposure;
- non-converters remain in the denominator;
- follow-up windows are mature or comparable;
- joins cannot multiply units;
- allocation, duplicates, null IDs, and data lag are monitored;
- every large table has a bounded predicate;
- query tags, warehouse usage, and credits are visible;
- statistical inference uses a tested implementation;
- metric changes are owned, reviewed, and versioned.
Snowflake SQL is the executable expression of an experiment's population and metric rules. Treat it like production code: make assumptions explicit, test the grain, preserve zeroes, bound time, inspect cost, and reconcile against a known result. Then use a shared analysis layer to apply consistent statistics and retain the decision.
Scale beyond Snowflake SQL
Reuse governed warehouse metrics, inspect every generated query, and give teams a consistent path from exposure to decision.
Build with GrowthBookRelated Articles
Ready to ship faster?
No credit card required. Start with feature flags, experimentation, and product analytics—free.


