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

Final lab: recover orders and preserve a historical QA baseline

Recover a deliberate deletion, preserve later valid writes and prove that a historical QA environment is independent from the repaired source.

Your learning goal

Explain every incident decision, recover five correct orders totaling 590, preserve a four-order historical QA baseline and document cleanup and remaining risks.

Understand the idea

A concrete example

You are the on-call engineer for a shop. A scheduled cleanup accidentally deletes all west orders. The business continues processing east orders. Your job is to repair the specific loss, keep current valid work and leave a reproducible environment for investigating the faulty predicate.

Key ideas in simple English
ConceptWhat it means
StartFour orders, four unique keys, total 500.
After incident and valid workThree orders, total 340.
After approved repairFive unique orders, total 590; 104=60 and 105=80 remain.
Historical QAFour orders, total 500 before QA experimentation.

Remember: Recovery is complete when the current business state is correct and the evidence explains why, not merely when missing rows reappear.

Explain it step by step · full theory

Learning objectives and prerequisites

Explain every incident decision, recover five correct orders totaling 590, preserve a four-order historical QA baseline and document cleanup and remaining risks.

Build on Modules 02–04: storage, table types, SELECT, DML and transactions. Module 13 explains why recovery must preserve valid business history. Use the first lesson’s isolated setup; examples name separate demonstration tables so the baseline ORDERS stays unchanged.

Prerequisites and safe execution contract

Complete lessons 1–11 or read their recovery and cloning decisions first. Use Standard Edition or higher with one-day retained ordinary permanent tables, an authorized warehouse and permission to create tables and the M14_FINAL_QA schema. No Enterprise-only feature is required.

This lab uses its own FINAL_ORDERS data, so it does not depend on earlier destructive demonstrations. M14_LAB must exist. CREATE statements intentionally fail if names exist; inspect a previous run or choose consistent fresh names instead of adding OR REPLACE. Run in one session without concurrent writers and within the retention window.

Do not run all blocks blindly as one script. The transaction block deliberately stops before COMMIT. Inspect results, then run either COMMIT or ROLLBACK separately. DDL setup and snapshot creation are kept outside that transaction.

Incident brief and recovery acceptance

Baseline: 101 west 100, 102 east 200, 103 west 150 and 104 east 50, all paid. The wrong DELETE removes 101 and 103. Then a legitimate correction sets 104 to 60, and a new order 105 for 80 arrives.

The correct recovered state is the original four orders with 104 corrected, plus 105: total 590. The pre-incident state totals 500 and is evidence, not the desired final current state. Explicitly reject any solution that replaces FINAL_ORDERS wholesale with the old snapshot.

Investigate, freeze and review

Capture the DELETE ID immediately and persist it in FINAL_INCIDENT_LOG. If your session is lost, inspect that log and set the session variable again to the exact stored ID. Do not use the latest query ID from an unrelated SELECT.

Inspect BEFORE the incident; then create a historical QA baseline and a current-state evidence clone. Select only the approved keys 101 and 103 into FINAL_REPAIR. Compare the two candidate records with the business evidence. Duplicate checks must return no rows before you begin repair.

  1. Confirm the baseline and available retention.
  2. Simulate the wrong DELETE and save its query ID.
  3. Apply the two explicit legitimate later changes.
  4. Read historical rows and confirm the damaged current total is 340.
  5. Create QA baseline and current evidence outside BEGIN.
  6. Review the two candidates and check key uniqueness.

Repair, validate and decide

Insert missing approved keys inside an explicit transaction. Inspect count, distinct-key count, total, exact field comparisons and duplicate checks. The expected mismatch and duplicate queries return no rows. That combination is stronger than checking SUM alone.

If any check differs, ROLLBACK and preserve evidence. If all checks match, COMMIT separately. A failed statement does not mean your entire incident decision is correct; verify transaction state and do not leave the worksheet with an open transaction.

After commit, record recovery evidence and test the QA working copy. The historical baseline remains unchanged. In production, also validate downstream streams, tasks, dynamic tables and reporting expectations before resuming writers; a data fix can create new downstream changes.

Cost and operational closure

Clones initially share existing storage, but repair writes, QA changes and historical retention can retain additional data. Queries and validations consume warehouse compute. The fixture is intentionally tiny and is not a performance or storage benchmark.

Keep the incident record and approved evidence for your required review period. Give QA objects an owner and expiration. Drop only this module’s disposable schemas/databases after review; deletion does not necessarily clear historical storage immediately. Never drop the shared L2_OBJECTS_LAB database just to clean up Module 14.

Troubleshooting the final lab

If BEFORE fails, check that the saved ID is the DELETE on FINAL_ORDERS, the same underlying table still exists, and history is still eligible. If the session variable is unset, read the persisted log; if you started a different run, do not mix its IDs.

If candidate count is not two, stop. ORDER_ID reuse, a rerun, concurrent changes or the wrong incident scope may have invalidated assumptions. If schema creation or cloning is denied, ask for approved lab permissions rather than granting your role broad production access.

For a read-only learning alternative, trace the supplied rows through each step: the damaged current 340 plus approved missing amounts 100 and 150 equals 590. Explain why the repaired total differs from the historical 500 without treating the difference as an error.

Production decisions and common mistakes

Recovery is complete when the current business state is correct and the evidence explains why, not merely when missing rows reappear.

Do not promote the historical QA table wholesale into production or commit solely because a command returned success.

Key takeaways

Explain that the missing west orders were restored from a saved pre-delete boundary, while valid current orders were preserved. Show exact values, uniqueness and aggregate checks, document transaction completion and identify remaining production controls such as concurrency and downstream reconciliation.

Words used in this lesson
Evidence baseline
A preserved historical snapshot used to justify the repair.
Current-state evidence
A snapshot of the damaged table including legitimate later work.
Acceptance criteria
Exact conditions that must hold before the repair is accepted.
QA working copy
A separate writable clone used without editing the evidence baseline.

See how it works

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

Open the interactive explanation
Interactive explainer1 / 4

Final lab: recover orders and preserve a historical QA baseline

Baseline
  • 4 orders · 500
Historical / retained
After DELETE
  • 2 orders · 250
Changed / needs review

Baseline and incident

The final lab begins with four orders totaling 500. The bad DELETE removes west orders. Capture its ID before issuing another diagnostic statement.

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. Baseline and incident

    The final lab begins with four orders totaling 500. The bad DELETE removes west orders. Capture its ID before issuing another diagnostic statement.

    • Baseline: 4 orders · 500
    • After DELETE: 2 orders · 250
  2. New work arrives

    Order 104 increases from 50 to 60 and order 105 arrives for 80. The damaged current table now has three rows totaling 340.

    • Current: 102 · 200; 104 · 60; 105 · 80
  3. Recover selectively

    Clone BEFORE the incident into QA. Validate the repair set, then insert only 101 and 103 while writers are coordinated. A blanket replacement would revert good work.

    • QA evidence: 101 · 100; 103 · 150
    • Repair target: Add approved missing keys
  4. Prove recovery and isolation

    Current production-like data totals 590, while the historical QA clone stays at 500 until intentionally edited. Check that a QA-only edit leaves the source unchanged.

    • Recovered source: 5 keys · 590
    • Historical QA: 4 keys · 500
    • Close incident: Record evidence; Clean up lab only

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 Snowflake practice only; SQL has not been executed for this course. Use an authorized warehouse and role with access to L2_OBJECTS_LAB and CREATE SCHEMA/CREATE TABLE as needed. Run in M14_LAB, in one session with one writer, using autocommit unless a transaction is shown. Run CREATE once, never replace an existing production object. Standard Edition with one-day retention is sufficient for the main lab; longer retention and administrative monitoring have separate requirements.

1. Create the independent final-lab fixture

Definition: A new target and incident log make the run inspectable.

When to use: After lesson 1 creates the database and M14_LAB schema.

SQL · example
-- Run after lesson 1. If skipped, run that lesson's setup first.
USE SCHEMA L2_OBJECTS_LAB.M14_LAB;
ALTER SESSION SET QUERY_TAG='learnsnowflake_m14';
CREATE TABLE FINAL_ORDERS (
 ORDER_ID NUMBER, REGION VARCHAR, AMOUNT NUMBER(10,2), STATUS VARCHAR
) DATA_RETENTION_TIME_IN_DAYS=1;
INSERT INTO FINAL_ORDERS VALUES
 (101,'west',100,'paid'),(102,'east',200,'paid'),
 (103,'west',150,'paid'),(104,'east',50,'paid');
CREATE TABLE FINAL_INCIDENT_LOG (
 INCIDENT_ID VARCHAR, EVENT_TIME TIMESTAMP_LTZ, EVENT_NAME VARCHAR, DETAILS VARCHAR
);
SELECT COUNT(*) AS N,COUNT(DISTINCT ORDER_ID) AS UNIQUE_KEYS,SUM(AMOUNT) AS TOTAL
FROM FINAL_ORDERS;

What to expect and why

The four rows total 500, with four distinct ORDER_ID values.

Expected result for the supplied input (not live output)
NUNIQUE_KEYSTOTAL
44500.00

2. Simulate the incident and legitimate later changes

Definition: Separate the bad write from the two valid later writes.

When to use: Only the dedicated FINAL_ORDERS object is modified.

SQL · example
-- Deliberate failure ONLY in the new FINAL_ORDERS lab table.
DELETE FROM FINAL_ORDERS WHERE REGION='west';
SET final_incident_id=LAST_QUERY_ID();
-- Save the ID immediately; later SELECTs must not replace it.
INSERT INTO FINAL_INCIDENT_LOG
SELECT $final_incident_id,CURRENT_TIMESTAMP(),'BAD_DELETE','Approved missing keys: 101,103';
-- Simulate legitimate later business work:
UPDATE FINAL_ORDERS SET AMOUNT=60 WHERE ORDER_ID=104;
INSERT INTO FINAL_ORDERS VALUES(105,'east',80,'paid');
SELECT COUNT(*) AS N,SUM(AMOUNT) AS TOTAL FROM FINAL_ORDERS;
SELECT * FROM FINAL_ORDERS BEFORE(STATEMENT => $final_incident_id) ORDER BY ORDER_ID;

What to expect and why

After deletion the total is 250. Increasing 104 by 10 and adding 105=80 produces 340. BEFORE the incident returns four original rows.

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

3. Freeze evidence and approve candidate keys

Definition: Historical QA, current evidence and repair candidates serve different purposes.

When to use: Before beginning any repair transaction.

SQL · example
-- Create evidence outside the repair transaction (DDL commits separately).
CREATE SCHEMA L2_OBJECTS_LAB.M14_FINAL_QA;
USE SCHEMA L2_OBJECTS_LAB.M14_LAB;
CREATE TABLE L2_OBJECTS_LAB.M14_FINAL_QA.ORDERS_BASELINE CLONE FINAL_ORDERS
 BEFORE(STATEMENT => $final_incident_id);
CREATE TABLE FINAL_CURRENT_EVIDENCE CLONE FINAL_ORDERS;
CREATE TABLE FINAL_REPAIR AS
SELECT h.ORDER_ID,h.REGION,h.AMOUNT,h.STATUS
FROM L2_OBJECTS_LAB.M14_FINAL_QA.ORDERS_BASELINE h
WHERE h.ORDER_ID IN (101,103)
 AND NOT EXISTS(SELECT 1 FROM FINAL_ORDERS c WHERE c.ORDER_ID=h.ORDER_ID);
SELECT * FROM FINAL_REPAIR ORDER BY ORDER_ID;
SELECT ORDER_ID,COUNT(*) FROM FINAL_REPAIR GROUP BY ORDER_ID HAVING COUNT(*)<>1;
SELECT ORDER_ID,COUNT(*) FROM FINAL_ORDERS GROUP BY ORDER_ID HAVING COUNT(*)<>1;
SHOW GRANTS ON TABLE L2_OBJECTS_LAB.M14_FINAL_QA.ORDERS_BASELINE;

What to expect and why

FINAL_REPAIR must contain exactly 101=100 and 103=150. Both duplicate queries must be empty. The historical QA baseline has four rows totaling 500.

4. Apply the reviewed repair and inspect every check

Definition: A guarded missing-key insertion preserves existing current rows.

When to use: Single writer, reviewed candidates, and no automatic commit until you inspect.

SQL · example
-- Coordinate writers first. This teaching fixture has only one writer.
BEGIN;
INSERT INTO FINAL_ORDERS(ORDER_ID,REGION,AMOUNT,STATUS)
SELECT h.ORDER_ID,h.REGION,h.AMOUNT,h.STATUS FROM FINAL_REPAIR h
WHERE NOT EXISTS(SELECT 1 FROM FINAL_ORDERS c WHERE c.ORDER_ID=h.ORDER_ID);
SELECT COUNT(*) AS N,COUNT(DISTINCT ORDER_ID) AS UNIQUE_KEYS,SUM(AMOUNT) AS TOTAL
FROM FINAL_ORDERS;
SELECT * FROM FINAL_ORDERS ORDER BY ORDER_ID;
-- Expected no rows: missing keys or incorrect field values.
WITH expected(ORDER_ID,REGION,AMOUNT,STATUS) AS (
 SELECT * FROM VALUES (101,'west',100,'paid'),(102,'east',200,'paid'),
 (103,'west',150,'paid'),(104,'east',60,'paid'),(105,'east',80,'paid')
)
SELECT COALESCE(e.ORDER_ID,c.ORDER_ID) AS MISMATCH_KEY
FROM expected e FULL OUTER JOIN FINAL_ORDERS c ON e.ORDER_ID=c.ORDER_ID
WHERE e.ORDER_ID IS NULL OR c.ORDER_ID IS NULL
 OR e.REGION IS DISTINCT FROM c.REGION
 OR e.AMOUNT IS DISTINCT FROM c.AMOUNT
 OR e.STATUS IS DISTINCT FROM c.STATUS;
SELECT ORDER_ID,COUNT(*) FROM FINAL_ORDERS GROUP BY ORDER_ID HAVING COUNT(*)<>1;
-- STOP and inspect all outputs. Execute exactly one separately:
-- COMMIT;
-- ROLLBACK;

What to expect and why

Review five distinct keys, exact expected values and the arithmetic in the result table. The exact comparison and duplicate queries must return no rows.

Expected result for the supplied input (not live output)
ORDER_IDREGIONAMOUNTSTATUS
101west100.00paid
102east200.00paid
103west150.00paid
104east60.00paid
105east80.00paid

5. Record closure and test QA isolation

Definition: Keep the historical baseline untouched; experiment on another clone.

When to use: Only after a separately executed successful COMMIT.

SQL · example
INSERT INTO FINAL_INCIDENT_LOG
SELECT $final_incident_id,CURRENT_TIMESTAMP(),'REPAIR_COMMITTED','Validated exact keys and preserved later work';
CREATE TABLE L2_OBJECTS_LAB.M14_FINAL_QA.ORDERS_WORK
 CLONE L2_OBJECTS_LAB.M14_FINAL_QA.ORDERS_BASELINE;
UPDATE L2_OBJECTS_LAB.M14_FINAL_QA.ORDERS_WORK SET AMOUNT=1 WHERE ORDER_ID=101;
SELECT 'CURRENT' AS OBJECT_STATE,COUNT(*) AS N,SUM(AMOUNT) AS TOTAL FROM FINAL_ORDERS
UNION ALL
SELECT 'QA BASELINE',COUNT(*),SUM(AMOUNT) FROM L2_OBJECTS_LAB.M14_FINAL_QA.ORDERS_BASELINE
UNION ALL
SELECT 'QA WORK',COUNT(*),SUM(AMOUNT) FROM L2_OBJECTS_LAB.M14_FINAL_QA.ORDERS_WORK;
SELECT * FROM FINAL_INCIDENT_LOG ORDER BY EVENT_TIME;

What to expect and why

Changing QA WORK does not change the baseline or current source. QA WORK total is 401 because 100 was replaced with 1. Record your actual query IDs and observations rather than treating this displayed output as a live execution.

Expected result for the supplied input (not live output)
OBJECT_STATENTOTAL
CURRENT5590.00
QA BASELINE4500.00
QA WORK4401.00

6. Scoped cleanup after manual review

Definition: Cleanup removes only this module’s disposable scopes.

When to use: Optional after saving learning notes and finishing all transactions.

SQL · example
-- First finish any open repair transaction. Export your learning notes.
-- Inspect each scope; drop ONLY disposable objects created by this module.
SHOW SCHEMAS LIKE 'M14%' IN DATABASE L2_OBJECTS_LAB;
-- Uncomment only the scopes you created and no longer need:
-- DROP SCHEMA L2_OBJECTS_LAB.M14_FINAL_QA;
-- DROP SCHEMA L2_OBJECTS_LAB.M14_QA_COPY;
-- DROP SCHEMA L2_OBJECTS_LAB.M14_QA;
-- DROP SCHEMA L2_OBJECTS_LAB.M14_SCHEMA_COPY;
-- DROP SCHEMA L2_OBJECTS_LAB.M14_DROP_SCHEMA;
-- DROP DATABASE M14_DATABASE_COPY;
-- DROP DATABASE M14_CONTAINER_SOURCE;
-- DROP DATABASE M14_DROP_DATABASE;
-- Optional historical templates, if you executed them:
-- DROP SCHEMA L2_OBJECTS_LAB.M14_HIST_SCHEMA;
-- DROP DATABASE M14_HIST_DATABASE;
-- LAST: removes all Module 14 tables, evidence and the incident log:
-- DROP SCHEMA L2_OBJECTS_LAB.M14_LAB;
ALTER SESSION UNSET QUERY_TAG;
-- Do not drop L2_OBJECTS_LAB: other modules use it.
-- Suspend only a dedicated learning warehouse you own, or use auto-suspend.

What to expect and why

DROP commands are commented deliberately. Review each scope before executing it. Remaining historical or clone-retained storage can outlive the visible object; monitoring is delayed.

Check your understanding

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

Which action best preserves the legitimate correction to order 104?

Try it yourself

Write an incident review: root cause, affected IDs, chosen boundary, rejected full-replacement plan, exact validation, QA isolation and cleanup decision.

Compare your reasoning

Explain that the missing west orders were restored from a saved pre-delete boundary, while valid current orders were preserved. Show exact values, uniqueness and aggregate checks, document transaction completion and identify remaining production controls such as concurrency and downstream reconciliation.

Key takeaway

Recovery is complete when the current business state is correct and the evidence explains why, not merely when missing rows reappear.

Connect this lesson to the learning path

Official sources and curriculum

Module 14 · See module scope

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