Module 14 · Lesson 4 of 12Detailed study · about 30 min

Repair accidental deletes without losing new orders

Selective recovery restores approved missing records from a historical snapshot while leaving legitimate current records intact.

Your learning goal

Identify the missing keys, isolate recovery evidence, insert only approved missing rows and prove that later changes survive.

Understand the idea

A concrete example

The bad DELETE removes 101 and 103. Afterwards 104 changes from 50 to 60 and new order 105 arrives for 80. The correct repaired total is 590; restoring the original total of 500 would be wrong.

Key ideas in simple English
ConceptWhat it means
Evidence snapshotA named historical clone keeps a stable investigation result.
Repair scopeOnly keys confirmed as accidental losses.
Anti-joinSelect historical rows with no current matching key.
ValidationCheck duplicates, individual values and expected totals before commit.

Remember: Preserve a current-state fallback and the incident evidence, then repair the smallest reviewed scope. Keep writers coordinated until verification finishes.

Explain it step by step · full theory

Learning objectives and prerequisites

Identify the missing keys, isolate recovery evidence, insert only approved missing rows and prove that later changes survive.

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.

Detect and freeze the evidence

A drop in a dashboard is a symptom, not an approved repair list. Compare the business expectation with Query History, the offending predicate and source events. In this lab the predicate REGION=west is known to be the mistake and the two affected IDs are explicitly approved.

Create a historical clone before repairing. It is a named, inspectable snapshot for the incident, not just a SELECT result left in a worksheet tab. Restrict who can change it and keep the incident ID in notes; a writable clone is not tamper-proof evidence.

Why full replacement is dangerous

A whole-table replacement from BEFORE the deletion would restore 101 and 103, but revert 104 to 50 and remove 105. It can also change object identity and affect dependent pipelines. Correct recovery is an intentional combination of historical evidence and valid current work.

The anti-join finds rows absent now; it does not determine whether their absence is a mistake. Always combine it with an approved key set or verified incident predicate. Otherwise you may resurrect a valid cancellation that happened after the snapshot.

Plan a controlled write

Materialize the approved repair set before BEGIN: creating tables is DDL and should not be mixed into the repair transaction. Validate unique keys in both current and candidate data. Standard-table primary keys are not a concurrency lock.

Coordinate or pause writers through your operational process. The lab has one writer; NOT EXISTS is not a general guarantee against concurrent duplicate inserts. If writers cannot pause, use application-specific version checks and conflict handling instead of copying this exercise as a production runbook.

  1. Identify incident and impacted IDs.
  2. Freeze the historical snapshot.
  3. Review missing-key candidates and duplicates.
  4. Start the repair transaction only after coordinating writers.
  5. Insert missing approved keys, inspect values and totals.
  6. Commit only after validation; otherwise ROLLBACK and investigate.

Validate more than one aggregate

Five rows and a total of 590 are necessary here, but an aggregate can hide one missing row and one duplicate row. Check every ORDER_ID, check COUNT DISTINCT, and explicitly assert the legitimate values 104=60 and 105=80.

If repair candidates are empty, check whether the rows were already repaired, the selected incident is wrong, or the keys are present with damaged values. Missing-row recovery is not the same operation as correcting existing values.

Production decisions and common mistakes

Preserve a current-state fallback and the incident evidence, then repair the smallest reviewed scope. Keep writers coordinated until verification finishes.

A NOT EXISTS condition prevents duplicates only under the stated execution assumptions; it is not an enforced uniqueness constraint or business approval.

Key takeaways

No. Compare business events and exclude legitimate subsequent cancellations from the approved repair set. Historical existence alone is not permission to restore a row.

Words used in this lesson
Anti-join
A query selecting rows with no matching row in another relation.
Candidate set
Approved records proposed for recovery.
Conflict
Current data no longer matches the assumptions used to plan a repair.
Evidence clone
A named snapshot for inspection, with restricted write access in production.

See how it works

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

Open the interactive explanation
Interactive explainer1 / 4

Repair accidental deletes without losing new orders

Current
  • 102 · 200
  • 104 · 50
Changed / needs review
Before incident
  • 101 · 100
  • 102 · 200
  • 103 · 150
  • 104 · 50
Historical / retained

Detect the loss

Two west-region orders disappeared. A row count alone does not tell you which missing records are legitimate deletions; inspect the incident predicate and business evidence.

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. Detect the loss

    Two west-region orders disappeared. A row count alone does not tell you which missing records are legitimate deletions; inspect the incident predicate and business evidence.

    • Current: 102 · 200; 104 · 50
    • Before incident: 101 · 100; 102 · 200; 103 · 150; 104 · 50
  2. Preserve legitimate later changes

    Order 104 is legitimately corrected to 60 and new order 105 arrives for 80. Replacing the whole table with the old state would destroy both changes.

    • Current after valid work: 102 · 200; 104 · 60; 105 · 80
    • Historical difference: 104 was 50; 105 did not exist
  3. Build a narrow repair set

    Freeze an incident snapshot, select only approved missing keys 101 and 103, and use an anti-join to avoid reinserting existing keys. Coordinate writers before changing current data.

    • Approved repair: 101 · 100; 103 · 150
    • Leave untouched: 102 · 200; 104 · 60; 105 · 80
  4. Reconcile the repaired state

    Five unique orders total 590. The correct result is neither the old 500 nor the damaged 340. Check individual keys and preserved changes as well as the aggregate.

    • Recovered: 101 · 100; 102 · 200; 103 · 150; 104 · 60; 105 · 80
    • Validation: 5 distinct keys; Total = 590

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.

Simulate loss and preserve valid later work

Definition: The source snapshot is taken before the bad DELETE; the current table continues to evolve.

When to use: A new disposable DELETE_ORDERS table after lesson 1.

SQL · example
USE SCHEMA L2_OBJECTS_LAB.M14_LAB;
CREATE TABLE DELETE_ORDERS CLONE ORDERS;
DELETE FROM DELETE_ORDERS WHERE REGION='west';
SET delete_incident_id=LAST_QUERY_ID();
-- Legitimate work after the incident:
UPDATE DELETE_ORDERS SET AMOUNT=60 WHERE ORDER_ID=104;
INSERT INTO DELETE_ORDERS VALUES(105,'east',80,'paid');
CREATE TABLE DELETE_EVIDENCE CLONE DELETE_ORDERS
 BEFORE(STATEMENT => $delete_incident_id);
SELECT COUNT(*) AS N, SUM(AMOUNT) AS TOTAL FROM DELETE_ORDERS;

What to expect and why

The current table has 102=200, 104=60 and 105=80: three rows totaling 340. DELETE_EVIDENCE has the original four rows totaling 500.

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

Review and apply a narrow repair

Definition: A candidate table isolates the approved missing records before the repair transaction.

When to use: Single-writer exercise; execute the validation statements before choosing COMMIT.

SQL · example
CREATE TABLE DELETE_REPAIR AS
SELECT h.ORDER_ID,h.REGION,h.AMOUNT,h.STATUS
FROM DELETE_EVIDENCE h
WHERE h.ORDER_ID IN (101,103)
 AND NOT EXISTS(SELECT 1 FROM DELETE_ORDERS c WHERE c.ORDER_ID=h.ORDER_ID);
SELECT * FROM DELETE_REPAIR ORDER BY ORDER_ID;
SELECT ORDER_ID,COUNT(*) FROM DELETE_REPAIR GROUP BY ORDER_ID HAVING COUNT(*)<>1;
-- Expect two candidates, no duplicate rows. Coordinate writers first.
BEGIN;
INSERT INTO DELETE_ORDERS (ORDER_ID,REGION,AMOUNT,STATUS)
SELECT h.ORDER_ID,h.REGION,h.AMOUNT,h.STATUS FROM DELETE_REPAIR h
WHERE NOT EXISTS(SELECT 1 FROM DELETE_ORDERS c WHERE c.ORDER_ID=h.ORDER_ID);
SELECT * FROM DELETE_ORDERS ORDER BY ORDER_ID;
SELECT COUNT(*) AS N,COUNT(DISTINCT ORDER_ID) AS UNIQUE_KEYS,SUM(AMOUNT) AS TOTAL
FROM DELETE_ORDERS;
-- STOP: inspect results. Run ONE command separately:
-- COMMIT;   -- only if correct
-- ROLLBACK; -- if any check fails

What to expect and why

Before commit, expect five distinct orders and total 590. Explicitly verify 104=60 and 105=80. Do not leave the transaction open after review. A retry with no intervening writes inserts nothing because the keys now exist.

Expected result for the supplied input (not live output)
ORDER_IDAMOUNT
101100.00
102200.00
103150.00
10460.00
10580.00

Check your understanding

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

Which recovery result is correct after the valid later changes?

Try it yourself

Imagine order 103 was intentionally cancelled after the mistaken DELETE. Should the anti-join alone resurrect it?

Compare your reasoning

No. Compare business events and exclude legitimate subsequent cancellations from the approved repair set. Historical existence alone is not permission to restore a row.

Key takeaway

Preserve a current-state fallback and the incident evidence, then repair the smallest reviewed scope. Keep writers coordinated until verification finishes.

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