Module 04 · Lesson 16 of 16Detailed study · about 18 min

Lab: deduplicate, analyse and commit a batch

Apply deterministic ranking to a small event batch, calculate customer totals, then commit the chosen records as one controlled operation.

Understand the idea

An ingestion batch may contain several versions of one order. Keeping an arbitrary row is not a deduplication rule. Here the latest timestamp wins; if timestamps tie, the greatest event ID wins. Event IDs must represent an agreed ordering rule, not a convenient accident.

Key ideas in simple English
ConceptWhat it means
Business keyORDER_ID identifies the logical order.
Tie-breakerEVENT_ID resolves equal update timestamps deterministically.
QUALIFYKeeps the selected version after ROW_NUMBER is computed.
TransactionLets you inspect and accept or discard the target writes.

A concrete example

Run once in a fresh learning session. The table starts empty and remains available only in this session.

Remember: Use the business key plus a complete, meaningful ordering rule. A successful deduplication SELECT does not by itself make repeated target inserts safe.

Explain it step by step · full theory

Let us understand the idea

An ingestion batch may contain several versions of one order. Keeping an arbitrary row is not a deduplication rule. Here the latest timestamp wins; if timestamps tie, the greatest event ID wins. Event IDs must represent an agreed ordering rule, not a convenient accident.

The fictional batch has two versions of order 101 and one version of order 102. The desired amounts are 45 and 60, so customer A totals 105. Source records remain unchanged: the query chooses which versions to insert into a separate target.

Reason through the SQL

Create the target before BEGIN. Within the transaction, insert the chosen rows and inspect them with a window total. First roll back to rehearse; then repeat with COMMIT only when the target and results match your expectation. This lab uses an empty target; replay-safe MERGE into an existing target belongs to pipeline design.

If a statement fails, run ROLLBACK in this session rather than assuming the error undid the whole operation. Do not rerun the INSERT after a successful commit without a strategy for existing target keys. Clean up the disposable table at the end.

Words used in this lesson
Business key
ORDER_ID identifies the logical order.
Tie-breaker
EVENT_ID resolves equal update timestamps deterministically.
QUALIFY
Keeps the selected version after ROW_NUMBER is computed.
Transaction
Lets you inspect and accept or discard the target writes.

See how it works

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

Open the interactive explanation
Interactive explainer1 / 3

Lab: deduplicate, analyse and commit a batch

Input rows
Business question

Begin with the question

Apply deterministic ranking to a small event batch, calculate customer totals, then commit the chosen records as one controlled operation.

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. Begin with the question

    Apply deterministic ranking to a small event batch, calculate customer totals, then commit the chosen records as one controlled operation.

  2. Choose the operation

    An ingestion batch may contain several versions of one order. Keeping an arbitrary row is not a deduplication rule. Here the latest timestamp wins; if timestamps tie, the greatest event ID wins. Event IDs must represent an agreed ordering rule, not a convenient accident.

  3. Check the meaning

    Use the business key plus a complete, meaningful ordering rule. A successful deduplication SELECT does not by itself make repeated target inserts safe.

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 capstone in one authorized learning session. Requires the Module 03 database/schema, CREATE TABLE and warehouse access. Run setup once. The rehearsal and commit alternatives are deliberately separate; do not execute both decisions for one transaction.

Create the disposable target

SQL · example
USE DATABASE L2_OBJECTS_LAB; USE SCHEMA SALES;
CREATE TEMPORARY TABLE M4_BATCH_TARGET
(ORDER_ID NUMBER, CUSTOMER VARCHAR, AMOUNT NUMBER(10,2));

What to expect and why

Run once in a fresh learning session. The table starts empty and remains available only in this session.

Choose the newest version and inspect the transaction

SQL · example
BEGIN TRANSACTION;
INSERT INTO M4_BATCH_TARGET (ORDER_ID,CUSTOMER,AMOUNT)
WITH events AS (
 SELECT COLUMN1 AS EVENT_ID, COLUMN2 AS ORDER_ID, COLUMN3 AS CUSTOMER,
 COLUMN4::TIMESTAMP_NTZ AS UPDATED_AT, COLUMN5 AS AMOUNT
 FROM VALUES
 (1,101,'A','2026-01-01 09:00:00',40),
 (2,101,'A','2026-01-01 10:00:00',45),
 (3,102,'A','2026-01-01 11:00:00',60)
)
SELECT ORDER_ID,CUSTOMER,AMOUNT FROM events
QUALIFY ROW_NUMBER() OVER (PARTITION BY ORDER_ID ORDER BY UPDATED_AT DESC, EVENT_ID DESC)=1;
SELECT ORDER_ID,CUSTOMER,AMOUNT,
 SUM(AMOUNT) OVER (PARTITION BY CUSTOMER) AS CUSTOMER_TOTAL
FROM M4_BATCH_TARGET ORDER BY ORDER_ID;
-- Rehearsal: discard this batch.
ROLLBACK;
SELECT COUNT(*) AS ROWS_AFTER_ROLLBACK FROM M4_BATCH_TARGET;

What to expect and why

Before rollback the rows are 101/A/45/105 and 102/A/60/105. After rollback the count is 0. Customer total repeats per order; summing that repeated column would double count.

Accept the batch and clean up

SQL · example
-- Repeat the preceding BEGIN / INSERT / inspection block.
-- Replace its ROLLBACK with this decision, not both:
COMMIT;
SELECT COUNT(*) AS ORDER_COUNT, SUM(AMOUNT) AS SALES FROM M4_BATCH_TARGET;
-- After recording the result:
DROP TABLE M4_BATCH_TARGET;

What to expect and why

After repeating the insert and committing instead of rolling back, ORDER_COUNT is 2 and SALES is 105. Running COMMIT alone after the rehearsal would not restore the discarded rows.

Check your understanding

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

What makes the latest-row choice deterministic when timestamps tie?

Try it yourself

Change the second event amount to 50 and predict the selected rows, total and rollback count.

Compare your reasoning

The selected amounts are 50 for order 101 and 60 for order 102. Each row shows customer total 110. After rollback, the empty target again has 0 rows.

Official sources and curriculum

Module 04 · See module scope