Module 15 · Lesson 14 of 14Detailed study · about 60 min

Final lab: investigate a slow regional revenue report

A defensible performance investigation produces a correct result, a measured baseline, an operator-based hypothesis and a comparable follow-up measurement.

Your learning goal

Investigate January paid revenue, compare equivalent SQL, preserve query evidence and recommend an optimization only when measurements justify it.

Understand the idea

A concrete example

The shop reports that January regional revenue is slow at busy times. Possible causes include poor pruning, a growing join, spill, queueing or a cold warehouse. Do not assume which cause applies before looking at evidence.

Key ideas in simple English
ConceptWhat it means
BaselineThe original correct query under recorded conditions.
HypothesisA specific explanation of expensive work that a change can test.
Controlled comparisonChange one factor while holding relevant conditions steady.
AcceptanceCorrect output plus agreed latency and consumption criteria.

Remember: A defensible conclusion connects correct output to exact query evidence and comparable conditions. No improvement is also a valid finding.

Explain it step by step · full theory

Learning goals and prerequisites

Investigate January paid revenue, compare equivalent SQL, preserve query evidence and recommend an optimization only when measurements justify it.

Use the M15_LAB setup from lesson 1. Know SELECT, joins, aggregates and window functions from Modules 03–04. Follow the supplied examples with an authorized warehouse and an isolated learning role. Keep the same data and account context when comparing runs.

The incident and scope

The shop reports that January regional revenue is slow at busy times. Possible causes include poor pruning, a growing join, spill, queueing or a cold warehouse. Do not assume which cause applies before looking at evidence.

This lab recreates the correct business query on a fresh six-row table. It cannot guarantee a slow execution. If your query is already fast, report that fact. Use the optional 100,000-row input from lesson 3 or an approved representative dataset for meaningful performance work, replacing the input in both variants consistently.

Prepare a controlled session

Complete lesson 1 setup or create the same six-row fixture in a fresh M15_LAB schema. Use one worksheet/session and a permitted warehouse. The lab creates FINAL_ORDERS and FINAL_CUSTOMERS from that fixture; use fresh names and keep them unchanged during comparisons.

Record current role, warehouse, size, generation, session parameters and business target. Save the prior USE_CACHED_RESULT and QUERY_TAG settings so you can restore them. This lab disables persisted reuse, but does not flush warehouse cache or force a cold start.

Capture the baseline and inspect Profile

Run the original query, immediately save its ID, then preserve its two result rows. Open that ID in Snowsight Query History → Profile. Inspect TableScan partitions and bytes, join input/output rows, aggregation, sort, spill and network categories.

For this fixture the January paid join has three rows and produces east=200 and west=250. If your join output is larger, investigate dimension uniqueness and predicates first. If queueing dominates, rewriting a date predicate may not address the complaint.

State one hypothesis and choose one change

The example candidate expresses the January filter as a half-open range and makes the needed columns explicit. It is intended to clarify scan requirements; the optimizer may already have produced the same plan for the baseline.

For a real workload, select the change supported by its expensive operator: fix join multiplicity, reduce unnecessary input, evaluate clustering for repeated selective scans, or compare resources for unavoidable spill. Do not enable several paid services together and then guess which helped.

Prove correctness and compare fairly

Compare both sets of regional results. Save candidate and baseline IDs, profile observations and actual timings. Repeat A/B runs under comparable conditions and include several warmed observations; retain query IDs for every repetition.

A single faster run is weak evidence. If scanned partitions, operators and execution remain similar, the rewrite may offer readability without measurable performance improvement. If the workload differs from the fixture, validate business grain, null handling and duplicate multiplicity as well as these aggregated rows.

Write an engineering recommendation

Your report should name the symptom, evidence, hypothesis, change, result-equivalence check, run conditions and remaining uncertainty. Include query frequency and a plan to measure warehouse/service consumption over a representative period.

Keep the optimization only if correctness and delivery targets hold and the cost trade-off is acceptable. Monitor the same workload after the change; changing query mix can invalidate a naive before/after comparison. Export your evidence before deleting lab objects.

Fill in your own investigation record

Fill in your own investigation record
EvidenceBaselineCandidate
Query IDRecord from your runRecord from your run
Data / warehouse / concurrent loadRecord conditionsKeep comparable
Elapsed / compile / queue / execute (ms)Record measured valuesRecord measured values
Scan partitions / total / bytesInspect scan evidenceInspect scan evidence
Join input/output and spillInspect ProfileInspect Profile
Exact regional outputeast 200; west 250east 200; west 250
Repeat runs and uncertaintyRecord each IDNo fabricated speedup
Consumption over representative workloadMeasure warehouse and service usageInclude maintenance and idle periods

Common mistakes and next action

A correct investigation can disprove a hypothesis. Report measured evidence and limitations honestly.

A defensible conclusion connects correct output to exact query evidence and comparable conditions. No improvement is also a valid finding.

Words used in this lesson
Baseline
The original correct query under recorded conditions.
Hypothesis
A specific explanation of expensive work that a change can test.
Controlled comparison
Change one factor while holding relevant conditions steady.
Acceptance
Correct output plus agreed latency and consumption criteria.

See how it works

Choose a step to explore the idea at your own pace.

Open the interactive explanation
Interactive explainer1 / 5

Final lab: investigate a slow regional revenue report

6 orders
January paid = 450
Saved settings

Establish

Define the correct regional report and record its environment.

Automatic playback is off for reduced motion. Select any step or use Previous and Next. Illustrations explain behavior; they are not live measurements.

Read the complete diagram explanation
  1. Establish

    Define the correct regional report and record its environment.

    6 orders → January paid = 450 → Saved settings

  2. Inspect

    Save baseline ID and find the expensive phase/operator.

    Queue or execution? → Scan / join / spill → One hypothesis

  3. Change

    Test an equivalent candidate while holding relevant conditions steady.

    Same data → One change → New query ID

  4. Validate

    Compare rows both ways and record real metrics; equal plans are a valid result.

    east 200 → west 250 → Measured evidence

  5. Recommend

    Weigh repeatable gains, maintenance and cost before keeping the change.

    • Keep the change if: Output is correct; Repeatable gains meet the target; Costs fit the workload
    • Revise the hypothesis if: Same plan and similar runtime; Queueing dominates; Maintenance outweighs read savings

Try the SQL or command

Read → predict → run in your learning environment → compare. You can also learn by reading without an account.

New to SQL? Where to run it and how to read it

A query is a question written in SQL. Snowflake runs it and returns a result table. This website shows examples; it does not connect to your account.

  1. No account yet? Read and predict the output first. Follow the account and Snowsight lesson when you are ready.
  2. For SQL practice, use a learning account in Snowsight and select an authorized role and warehouse. A role determines permissions; a warehouse supplies processing power. Follow the example’s database/schema setup when it refers to stored objects.
  3. Read the entire example, including comments beginning with --. Run the selected statement or labeled block in the stated order. Examples labeled Python, shell or HTTP belong in that client, not in a SQL editor.
  4. Compare values and row counts with the explained result. If an example deliberately causes an error, follow its rollback and cleanup steps before continuing.
SELECT / FROM
Choose the values to return / identify their input.
VALUES / COLUMN1
VALUES supplies tiny example rows. COLUMN1 means their first column, COLUMN2 their second.
AS / WITH
AS gives a result a readable name. WITH names a temporary query step within one statement.
NULL / ::
NULL means missing or unknown. The :: notation converts a value to a named data type.
Session
One connection and its settings. Keep related transaction steps in the same session.
Database.schema.table
A full address for stored data. It is separate from the warehouse that processes queries.

Need the L2_OBJECTS_LAB setup? Open the first database-object lesson →

Help with common practice errors
  • No active warehouse: select a warehouse your role can use. Do not assume you need to create a new one.
  • Object missing or not authorized: check the full name, required setup and active role. Ask the account owner for access if needed.
  • Object already exists: setup may already have run. Read the current state or choose a fresh lab name consistently; do not add OR REPLACE blindly.
  • Different result: check whether an earlier INSERT or UPDATE changed the data. VALUES examples provide their own fresh input for each statement.

Before running this lesson

Manual examples for L2_OBJECTS_LAB.M15_LAB. Select an authorized warehouse and a role with database/schema access and permission to create the lab objects. Setup runs once with fresh names. Optional paid services require their stated privileges and edition. SQL and performance timings have not been executed or measured for this lesson.

Prepare fresh final-lab tables

SQL · example
USE DATABASE L2_OBJECTS_LAB;
USE SCHEMA M15_LAB;
CREATE TABLE FINAL_ORDERS CLONE ORDERS;
CREATE TABLE FINAL_CUSTOMERS CLONE CUSTOMERS;
SELECT CURRENT_ROLE(),CURRENT_WAREHOUSE();
SHOW PARAMETERS LIKE 'USE_CACHED_RESULT' IN SESSION;
SHOW PARAMETERS LIKE 'QUERY_TAG' IN SESSION;
SELECT COUNT(*) AS N,SUM(AMOUNT) AS TOTAL FROM FINAL_ORDERS;

What to expect and why

Requires lesson 1 unchanged fixture. Expect six orders totaling 700; otherwise stop and restore an isolated fixture from the lesson 1 records before comparing. Clones can retain storage after changes, as Module 14 explains.

Expected result for the supplied input (not live output)
NTOTAL
6700.00

Baseline: save the exact query ID

SQL · example
ALTER SESSION SET USE_CACHED_RESULT=FALSE;
ALTER SESSION SET QUERY_TAG='learnsnowflake_m15_baseline';
SELECT c.REGION,SUM(o.AMOUNT) AS REVENUE
FROM FINAL_ORDERS o JOIN FINAL_CUSTOMERS c
 ON o.CUSTOMER_ID=c.CUSTOMER_ID
WHERE YEAR(o.ORDER_DATE)=2026 AND MONTH(o.ORDER_DATE)=1
 AND o.STATUS='paid'
GROUP BY c.REGION ORDER BY c.REGION;
SET baseline_query_id=LAST_QUERY_ID();
CREATE TEMPORARY TABLE BASELINE_RESULT AS
 SELECT * FROM TABLE(RESULT_SCAN($baseline_query_id));

What to expect and why

Capture immediately after the SELECT, before another statement changes LAST_QUERY_ID. RESULT_SCAN preserves these result rows within the same authorized session/user context.

Candidate: explicit range and projection

SQL · example
ALTER SESSION SET QUERY_TAG='learnsnowflake_m15_candidate';
WITH january_paid AS (
 SELECT CUSTOMER_ID,AMOUNT FROM FINAL_ORDERS
 WHERE ORDER_DATE>='2026-01-01'::DATE AND ORDER_DATE<'2026-02-01'::DATE
 AND STATUS='paid'
)
SELECT c.REGION,SUM(o.AMOUNT) AS REVENUE
FROM january_paid o JOIN FINAL_CUSTOMERS c ON o.CUSTOMER_ID=c.CUSTOMER_ID
GROUP BY c.REGION ORDER BY c.REGION;
SET candidate_query_id=LAST_QUERY_ID();
CREATE TEMPORARY TABLE CANDIDATE_RESULT AS
 SELECT * FROM TABLE(RESULT_SCAN($candidate_query_id));

What to expect and why

Expected output is identical. This is a testable rewrite, not a guaranteed speed improvement.

Expected result for the supplied input (not live output)
REGIONREVENUE
east200.00
west250.00

Validate both directions and expected values

SQL · example
SELECT * FROM BASELINE_RESULT MINUS SELECT * FROM CANDIDATE_RESULT;
SELECT * FROM CANDIDATE_RESULT MINUS SELECT * FROM BASELINE_RESULT;
SELECT COUNT(*) AS REGIONS,SUM(REVENUE) AS TOTAL FROM CANDIDATE_RESULT;
SELECT * FROM CANDIDATE_RESULT ORDER BY REGION;

What to expect and why

Both MINUS statements should return zero rows. Expect two regions totaling 450, with east 200 and west 250. Aggregation produces one row per region here, so a set comparison checks the complete result; arbitrary duplicate-bearing outputs need multiplicity checks too.

Measure the exact pair

SQL · example
SELECT QUERY_ID,QUERY_TAG,TOTAL_ELAPSED_TIME,COMPILATION_TIME,EXECUTION_TIME,
 QUEUED_OVERLOAD_TIME,QUEUED_PROVISIONING_TIME,
 PARTITIONS_SCANNED,PARTITIONS_TOTAL,BYTES_SCANNED,
 PERCENTAGE_SCANNED_FROM_CACHE,BYTES_SPILLED_TO_LOCAL_STORAGE,
 BYTES_SPILLED_TO_REMOTE_STORAGE,BYTES_SENT_OVER_THE_NETWORK
FROM TABLE(L2_OBJECTS_LAB.INFORMATION_SCHEMA.QUERY_HISTORY_BY_SESSION(RESULT_LIMIT=>1000))
WHERE QUERY_ID IN ($baseline_query_id,$candidate_query_id);

What to expect and why

Fill in your own observations; no fabricated runtime result is provided. Limits are applied before the WHERE filter, so narrow the session/time window or increase the supported result limit if an older query is missing.

Clean up only after saving the investigation

SQL · example
-- Restore the exact session settings recorded at the start.
-- Typical defaults are shown only as examples:
-- ALTER SESSION SET USE_CACHED_RESULT=TRUE;
-- ALTER SESSION UNSET QUERY_TAG;
-- DROP TABLE L2_OBJECTS_LAB.M15_LAB.FINAL_ORDERS;
-- DROP TABLE L2_OBJECTS_LAB.M15_LAB.FINAL_CUSTOMERS;
-- DROP TABLE L2_OBJECTS_LAB.M15_LAB.BASELINE_RESULT;
-- DROP TABLE L2_OBJECTS_LAB.M15_LAB.CANDIDATE_RESULT;
-- When ALL Module 15 work is finished and the scope has been reviewed:
-- DROP SCHEMA L2_OBJECTS_LAB.M15_LAB;

What to expect and why

Cleanup is deliberately commented. Dropping this isolated schema also removes optional lab views/tables and their future maintenance. Do not drop L2_OBJECTS_LAB or other modules. Retained storage and already consumed credits are not instantly erased.

Check your understanding

Choose an answer, then check your reasoning. This is practice, not a scored test.

What should you report if the two queries have the same plan and similar measured performance?

Try it yourself

Write a short incident report with query IDs, output checks, operator observations, repeat-run conditions, chosen action and cost-monitoring plan.

Compare your reasoning

A defensible conclusion connects correct output to exact query evidence and comparable conditions. No improvement is also a valid finding.

Key takeaway

A defensible conclusion connects correct output to exact query evidence and comparable conditions. No improvement is also a valid finding.

Connect this lesson to the learning path

Official sources and curriculum

Module 15 · See module scope

By Rohit Ray · Independent educational lesson · Explore this visual lab