Recover incorrect updates and truncated data
An UPDATE repair restores damaged columns; a TRUNCATE repair restores missing records while respecting valid data added afterwards.
Your learning goal
Choose the correct repair granularity and explain why restoring rows after TRUNCATE does not restore load metadata.
Understand the idea
A concrete example
Order 101’s amount is accidentally set to zero, then fulfilment correctly marks the order shipped. Replacing the full historical row would bring back the amount but undo shipment status.
| Concept | What it means |
|---|---|
| Bad UPDATE | Recover selected columns, with guards against overwriting newer work. |
| TRUNCATE | Removes table rows; the table object remains. |
| Pre-truncate evidence | Use a known earlier SELECT query ID, avoiding a DDL query ID as the STATEMENT reference. |
| Load metadata | TRUNCATE clears file-load metadata; row recovery does not rebuild it. |
Remember: Choose the smallest recovery unit that fixes the incident and verify unrelated current fields remain unchanged.
Explain it step by step · full theory
Learning objectives and prerequisites
Choose the correct repair granularity and explain why restoring rows after TRUNCATE does not restore load metadata.
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.
Restore the field that was wrong
Join current data to the pre-incident snapshot by a stable key. Update only AMOUNT, not every column. Include a guard such as current AMOUNT=0 when that value is the known erroneous state. This avoids silently replacing a later legitimate correction.
A guard is a conflict detector, not universal proof. A real system may need version numbers, audit timestamps and reviewed source events. If the update affects zero rows, do not remove the guard blindly; inspect why the state differs.
Keep evidence and writes separate
The example uses UPDATE_ORDERS, cloned from the unchanged baseline. The bad update query ID is captured immediately. A separate shipped status change represents valid later work. The repair restores 100 while keeping shipped.
Avoid CREATE OR REPLACE AS SELECT for a column repair. Besides overwriting valid values, replacement can change the table identity and invalidate dependencies. A narrow UPDATE is easier to review when the incident scope is one field.
TRUNCATE and recovery
TRUNCATE empties the table without dropping its definition. It also removes file-load metadata, which matters when COPY INTO later sees files previously loaded. Historical data can still be eligible for Time Travel; file-load metadata is not recovered by reinserting those rows.
The SQL captures a SELECT boundary after table setup and before TRUNCATE. This uses a supported STATEMENT reference rather than relying on the TRUNCATE DDL query ID. The single-writer exercise guarantees no other changes between the saved SELECT and the truncation.
Troubleshooting and safe retries
For a truncated table with later arrivals, insert only missing approved historical keys. If keys have been reused or the current schema changed, stop and design a conflict-aware mapping. Do not assume a successful INSERT proves the original contract is restored.
After recovery, review ingestion restart behavior. Cleared load history can permit file reloading, so reconcile source delivery IDs and deduplication rules from Modules 06 and 13. Recovering business records and restarting ingestion safely are separate tasks.
Production decisions and common mistakes
Choose the smallest recovery unit that fixes the incident and verify unrelated current fields remain unchanged.
Do not assume TRUNCATE is equivalent to DROP or that restoring row data also restores file-load history.
Key takeaways
Inspect the current key, amount and any later events. A zero-row result may mean a repair already happened or another valid correction superseded it. Resolve the conflict rather than widening the predicate.
Words used in this lesson
- Guard condition
- A condition requiring the current row to match an expected state before a repair.
- TRUNCATE
- Remove all rows while keeping the table definition.
- Load metadata
- Records used to identify previously loaded files.
- Repair granularity
- Whether you repair a field, row set or entire object.
See how it works
Choose a step to explore the idea at your own pace.
Open the interactive explanation
Recover incorrect updates and truncated data
- 101 · amount 100 · paid
- 101 · amount 0 · shipped
Incorrect update
AMOUNT on order 101 becomes zero. A later legitimate status change marks it shipped. Recover only the damaged column, not the entire historical row.
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
- Incorrect update
AMOUNT on order 101 becomes zero. A later legitimate status change marks it shipped. Recover only the damaged column, not the entire historical row.
- History: 101 · amount 100 · paid
- Current: 101 · amount 0 · shipped
- Column-level repair
Use the approved historical AMOUNT and an expected-current-value guard. A mismatch is a conflict to investigate, not a reason to overwrite blindly.
- Repair AMOUNT: 0 → 100
- Preserve STATUS: shipped → shipped
- TRUNCATE is a separate incident
In another disposable table, TRUNCATE removes all four rows but keeps the table. Later order 105 arrives. A historical snapshot provides the original four records.
- Before TRUNCATE: 4 rows · 500
- Current: 105 · 80
- Restore missing keys
Insert the four missing historical rows without deleting 105. Expect five rows totaling 580. Restoring table rows does not restore TRUNCATE’s deleted file-load metadata.
- Recovered table: Original four · 500; New order · 80
- Reconcile: 5 unique keys; Total = 580
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.
- No account yet? Read and predict the output first. Follow the account and Snowsight lesson when you are ready.
- 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.
- 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. - 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.
Repair an amount without reverting status
Definition: A column-level historical repair keeps unaffected current fields.
When to use: A fresh UPDATE_ORDERS table; one writer.
USE SCHEMA L2_OBJECTS_LAB.M14_LAB;
CREATE TABLE UPDATE_ORDERS CLONE ORDERS;
UPDATE UPDATE_ORDERS SET AMOUNT=0 WHERE ORDER_ID=101;
SET update_incident_id=LAST_QUERY_ID();
UPDATE UPDATE_ORDERS SET STATUS='shipped' WHERE ORDER_ID=101;
CREATE TABLE UPDATE_EVIDENCE CLONE UPDATE_ORDERS
BEFORE(STATEMENT => $update_incident_id);
BEGIN;
UPDATE UPDATE_ORDERS c SET AMOUNT=h.AMOUNT
FROM UPDATE_EVIDENCE h
WHERE c.ORDER_ID=h.ORDER_ID AND c.ORDER_ID=101 AND c.AMOUNT=0;
SELECT ORDER_ID,AMOUNT,STATUS FROM UPDATE_ORDERS WHERE ORDER_ID=101;
-- Inspect: then separately COMMIT; or ROLLBACK;What to expect and why
Expected amount is 100 and status stays shipped. Confirm the update affected exactly one row. Complete the transaction before running the next independent example.
| ORDER_ID | AMOUNT | STATUS |
|---|---|---|
| 101 | 100.00 | shipped |
Recover a truncated table with a later arrival
Definition: Use a captured pre-truncate SELECT ID as a stable historical boundary.
When to use: Fresh TRUNCATE_ORDERS; the baseline ORDERS remains untouched.
CREATE TABLE TRUNCATE_ORDERS CLONE ORDERS;
SELECT COUNT(*) FROM TRUNCATE_ORDERS;
SET pre_truncate_id=LAST_QUERY_ID();
TRUNCATE TABLE TRUNCATE_ORDERS;
INSERT INTO TRUNCATE_ORDERS VALUES(105,'east',80,'paid');
CREATE TABLE TRUNCATE_EVIDENCE CLONE TRUNCATE_ORDERS
AT(STATEMENT => $pre_truncate_id);
BEGIN;
INSERT INTO TRUNCATE_ORDERS(ORDER_ID,REGION,AMOUNT,STATUS)
SELECT h.ORDER_ID,h.REGION,h.AMOUNT,h.STATUS FROM TRUNCATE_EVIDENCE h
WHERE NOT EXISTS(SELECT 1 FROM TRUNCATE_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 TRUNCATE_ORDERS;
-- Inspect: then separately COMMIT; or ROLLBACK;What to expect and why
The original four total 500; the later row adds 80. Expect five distinct keys and total 580. No real files were loaded in this fixture; load-history implications are explained conceptually.
| N | UNIQUE_KEYS | TOTAL |
|---|---|---|
| 5 | 5 | 580.00 |
Check your understanding
Choose an answer, then check your reasoning. This is practice, not a scored test.
Try it yourself
Your guarded UPDATE affects no rows. What should you do before retrying?
Compare your reasoning
Inspect the current key, amount and any later events. A zero-row result may mean a repair already happened or another valid correction superseded it. Resolve the conflict rather than widening the predicate.
Key takeaway
Choose the smallest recovery unit that fixes the incident and verify unrelated current fields remain unchanged.
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