Module 11 · Lesson 10 of 15Detailed study · about 25 min

Consume, deduplicate and MERGE in one transaction

The processing procedure stages the current interval, validates it and updates target state before committing the stream offset with the data.

Understand the idea

MERGE needs an unambiguous source per target key. We first copy stream events into EVENT_BATCH inside the same transaction, then validate and select one highest version per order. Exact duplicate deliveries do not multiply target rows.

Key ideas in simple English
ConceptWhat it means
EVENT_BATCHDurable scratch table used by one serialized consumer.
ROW_NUMBERChooses one latest source version per business key.
Version guardOnly newer versions can change an existing target.
Atomic commitTarget writes and stream consumption succeed together.

A concrete example

No processing occurs until CALL. The failure switch exists only for the learning exercise.

Remember: Define one source decision per key and make the entire consuming operation transactional.

Explain it step by step · full theory

Understand the concept

MERGE needs an unambiguous source per target key. We first copy stream events into EVENT_BATCH inside the same transaction, then validate and select one highest version per order. Exact duplicate deliveries do not multiply target rows.

The target must already have at most one row per ORDER_ID. A standard-table key declaration alone would not enforce this invariant. Use a single writer and no overlapping processing; do not call this procedure manually while its task or graph is running.

Walk through the behavior

The procedure rejects null contract fields, unknown operations and differing same-version records within the batch. It assumes a producer never reuses a version with a different payload across batches; equal/older versions are ignored by the version guard. Production ingestion must enforce or audit that cross-batch producer contract as well.

EVENT_BATCH is prepared outside the procedure; DELETE is used rather than CREATE OR REPLACE or TRUNCATE DDL assumptions. The consuming INSERT, validation, MERGE and rollback all remain in one procedure-owned transaction. Call it outside an existing explicit transaction.

Words used in this lesson
EVENT_BATCH
Durable scratch table used by one serialized consumer.
ROW_NUMBER
Chooses one latest source version per business key.
Version guard
Only newer versions can change an existing target.
Atomic commit
Target writes and stream consumption succeed together.

See how it works

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

Open the interactive explanation
Interactive explainer1 / 3

Consume, deduplicate and MERGE in one transaction

Source data
Change boundary

Start with the source

The processing procedure stages the current interval, validates it and updates target state before committing the stream offset with the data.

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. Start with the source

    The processing procedure stages the current interval, validates it and updates target state before committing the stream offset with the data.

  2. Follow the work

    MERGE needs an unambiguous source per target key. We first copy stream events into EVENT_BATCH inside the same transaction, then validate and select one highest version per order. Exact duplicate deliveries do not multiply target rows.

  3. Explain the outcome

    Define one source decision per key and make the entire consuming operation transactional.

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 learning lab; nothing runs on this website. Complete lesson 1 setup in L2_OBJECTS_LAB.M11_LAB and follow the lesson order. Use the same authorized role and warehouse for manual SQL. Task templates use <lab_warehouse>: replace it with an approved warehouse name. Do not activate several consumers against the same stream. Each task starts suspended; running or resuming it can consume compute credits.

Create the serialized consumer procedure

SQL · example
CREATE PROCEDURE APPLY_EVENTS(FAIL_AFTER_MERGE BOOLEAN)
RETURNS VARCHAR LANGUAGE SQL EXECUTE AS CALLER AS $$
DECLARE bad_count NUMBER; bad_batch EXCEPTION (-20001,'Invalid or conflicting event contract');
 practice_failure EXCEPTION (-20002,'Intentional failure after MERGE');
BEGIN
 BEGIN TRANSACTION;
 DELETE FROM L2_OBJECTS_LAB.M11_LAB.EVENT_BATCH;
 INSERT INTO L2_OBJECTS_LAB.M11_LAB.EVENT_BATCH
 SELECT EVENT_ID,ORDER_ID,EVENT_VERSION,OP,AMOUNT FROM L2_OBJECTS_LAB.M11_LAB.EVENT_CHANGES;
 SELECT COUNT(*) INTO :bad_count FROM L2_OBJECTS_LAB.M11_LAB.EVENT_BATCH
 WHERE EVENT_ID IS NULL OR ORDER_ID IS NULL OR EVENT_VERSION IS NULL OR EVENT_VERSION < 1
 OR OP IS NULL OR OP NOT IN ('UPSERT','DELETE') OR (OP='UPSERT' AND AMOUNT IS NULL);
 IF (bad_count > 0) THEN RAISE bad_batch; END IF;
 SELECT COUNT(*) INTO :bad_count FROM (
 SELECT ORDER_ID,EVENT_VERSION FROM (
 SELECT DISTINCT ORDER_ID,EVENT_VERSION,EVENT_ID,OP,AMOUNT
 FROM L2_OBJECTS_LAB.M11_LAB.EVENT_BATCH
 ) GROUP BY ORDER_ID,EVENT_VERSION HAVING COUNT(*) > 1);
 IF (bad_count > 0) THEN RAISE bad_batch; END IF;
 MERGE INTO L2_OBJECTS_LAB.M11_LAB.ORDER_STATE t USING (
 SELECT ORDER_ID,EVENT_VERSION,EVENT_ID,OP,AMOUNT
 FROM L2_OBJECTS_LAB.M11_LAB.EVENT_BATCH
 QUALIFY ROW_NUMBER() OVER(PARTITION BY ORDER_ID ORDER BY EVENT_VERSION DESC,EVENT_ID DESC)=1
 ) s ON t.ORDER_ID=s.ORDER_ID
 WHEN MATCHED AND s.EVENT_VERSION > t.EVENT_VERSION THEN UPDATE SET
 EVENT_VERSION=s.EVENT_VERSION,EVENT_ID=s.EVENT_ID,
 AMOUNT=IFF(s.OP='DELETE',NULL,s.AMOUNT),IS_DELETED=(s.OP='DELETE')
 WHEN NOT MATCHED THEN INSERT (ORDER_ID,EVENT_VERSION,EVENT_ID,AMOUNT,IS_DELETED)
 VALUES(s.ORDER_ID,s.EVENT_VERSION,s.EVENT_ID,IFF(s.OP='DELETE',NULL,s.AMOUNT),s.OP='DELETE');
 IF (FAIL_AFTER_MERGE) THEN RAISE practice_failure; END IF;
 COMMIT;
 RETURN 'Batch committed';
EXCEPTION WHEN OTHER THEN
 ROLLBACK;
 RAISE;
END;
$$;

What to expect and why

No processing occurs until CALL. The failure switch exists only for the learning exercise.

Apply the first batch

SQL · example
CALL APPLY_EVENTS(FALSE);
SELECT * FROM ORDER_STATE ORDER BY ORDER_ID;
SELECT COUNT(*) FROM EVENT_CHANGES;
SELECT COUNT(*) FROM AUDIT_CHANGES;

What to expect and why

Target: 101/version2/120 and 102/version1/50, both active. EVENT_CHANGES has 0 rows; independent AUDIT_CHANGES still has 4.

Check your understanding

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

Why deduplicate before MERGE?

Try it yourself

Why must this implementation run with only one writer?

Compare your reasoning

It shares EVENT_BATCH and depends on one target row per key. Overlapping calls can conflict or violate those assumptions.

Official sources and curriculum

Module 11 · See module scope