Apply an incremental Type 2 batch atomically
The source window, accepted ledger, dimension history, watermark and successful-run audit must form one consistent commit.
Understand the idea
A naïve MERGE can match multiple source rows to one target or insert duplicates when nothing matches. We first validate business identity across new and accepted evidence, then collapse exact replays. Different payloads using one EVENT_ID fail the whole batch.
| Concept | What it means |
|---|---|
| Validate | Reject ambiguous keys and effective times. |
| Deduplicate | Collapse identical deliveries before inserting events. |
| Rebuild affected history | Use all accepted versions for each changed customer. |
| Commit boundary | Publish dimension, watermark and success audit together. |
A concrete example
A naïve MERGE can match multiple source rows to one target or insert duplicates when nothing matches. We first validate business identity across new and accepted evidence, then collapse exact replays. Different payloads using one EVENT_ID fail the whole batch.
Remember: Commit data and acknowledgement together; otherwise recovery may skip uncommitted changes.
Explain it step by step · full theory
Understand the concept
A naïve MERGE can match multiple source rows to one target or insert duplicates when nothing matches. We first validate business identity across new and accepted evidence, then collapse exact replays. Different payloads using one EVENT_ID fail the whole batch.
The procedure rebuilds only customers present in this delivery window. LEAD finds each version’s next effective timestamp. Reading the complete accepted history for those customers makes a late February event fit between January and March. This is incremental by affected key, not a constant-cost row-by-row algorithm.
Apply it in practice
Call this procedure outside another explicit transaction. DDL belongs outside the transaction; all tables were created earlier. Keep one writer because the scratch table and watermark are shared. Standard-table uniqueness declarations would not make concurrent execution safe.
The failure switch proves rollback before commit. After rollback a separate failure-log transaction preserves the error and the original error is raised. REJECT_LOG is a batch-error log, not a complete row quarantine; original INPUT_EVENTS retains the rejected evidence. Repair the source under a controlled process and retry the unadvanced window.
Production extraction must also enforce non-null unique DELIVERY_ID values and the closed-batch rule before landing. This lab treats those as input guarantees. Attribute deletion, same-time corrections and unchanged observations require an explicit extension; they are not silently guessed by the procedure.
Words used in this lesson
- Validate
- Reject ambiguous keys and effective times.
- Deduplicate
- Collapse identical deliveries before inserting events.
- Rebuild affected history
- Use all accepted versions for each changed customer.
- Commit boundary
- Publish dimension, watermark and success audit together.
See how it works
Choose a step to explore the idea at your own pace.
Open the interactive explanation
Apply an incremental Type 2 batch atomically
Understand the flow
The source window, accepted ledger, dimension history, watermark and successful-run audit must form one consistent commit.
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
- Understand the flow
The source window, accepted ledger, dimension history, watermark and successful-run audit must form one consistent commit.
- Apply the contract
Commit data and acknowledgement together; otherwise recovery may skip uncommitted changes.
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 learning exercise. Production deployment needs source-specific contracts, access controls, orchestration and operational monitoring.
Apply an incremental Type 2 batch atomically — SQL example
Definition: The source window, accepted ledger, dimension history, watermark and successful-run audit must form one consistent commit.
When to use: Follow the isolated customer-history lab in lesson order.
Example: Three versions: C1 Pune [Jan 1, Mar 1), C1 Mumbai [Mar 1, open), C2 Delhi [Jan 1, open). Watermark 4; one successful audit with 4 deliveries. Surrogate values are not predetermined.
CREATE PROCEDURE APPLY_CUSTOMER_BATCH(FAIL_BEFORE_COMMIT BOOLEAN)
RETURNS VARCHAR LANGUAGE SQL EXECUTE AS CALLER
AS $$
DECLARE
lo NUMBER; hi NUMBER; bad NUMBER; n NUMBER; err VARCHAR;
invalid_batch EXCEPTION(-20001,'Invalid or conflicting input batch');
forced_failure EXCEPTION(-20002,'Intentional learning failure');
BEGIN
BEGIN TRANSACTION;
SELECT LAST_DELIVERY INTO :lo FROM L2_OBJECTS_LAB.M13_LAB.PIPELINE_STATE;
SELECT COALESCE(MAX(DELIVERY_ID),:lo) INTO :hi FROM L2_OBJECTS_LAB.M13_LAB.INPUT_EVENTS;
DELETE FROM L2_OBJECTS_LAB.M13_LAB.BATCH_EVENTS;
INSERT INTO L2_OBJECTS_LAB.M13_LAB.BATCH_EVENTS
SELECT * FROM L2_OBJECTS_LAB.M13_LAB.INPUT_EVENTS WHERE DELIVERY_ID>:lo AND DELIVERY_ID<=:hi;
SELECT COUNT(*) INTO :n FROM L2_OBJECTS_LAB.M13_LAB.BATCH_EVENTS;
IF (n=0) THEN
COMMIT; RETURN 'No new deliveries';
END IF;
SELECT COUNT(*) INTO :bad FROM L2_OBJECTS_LAB.M13_LAB.BATCH_EVENTS
WHERE EVENT_ID IS NULL OR CUSTOMER_ID IS NULL OR CITY IS NULL OR EFFECTIVE_AT IS NULL
OR TRIM(EVENT_ID)='' OR TRIM(CUSTOMER_ID)='' OR TRIM(CITY)='';
IF (bad>0) THEN RAISE invalid_batch; END IF;
-- One event ID must describe exactly one business payload, including prior batches.
SELECT COUNT(*) INTO :bad FROM (
SELECT EVENT_ID FROM (
SELECT EVENT_ID,CUSTOMER_ID,CITY,EFFECTIVE_AT FROM L2_OBJECTS_LAB.M13_LAB.CUSTOMER_LEDGER
UNION SELECT EVENT_ID,CUSTOMER_ID,CITY,EFFECTIVE_AT FROM L2_OBJECTS_LAB.M13_LAB.BATCH_EVENTS
) GROUP BY EVENT_ID HAVING COUNT(*)>1
);
IF (bad>0) THEN RAISE invalid_batch; END IF;
-- The lab accepts one business event per customer/effective timestamp.
SELECT COUNT(*) INTO :bad FROM (
SELECT CUSTOMER_ID,EFFECTIVE_AT FROM (
SELECT EVENT_ID,CUSTOMER_ID,EFFECTIVE_AT FROM L2_OBJECTS_LAB.M13_LAB.CUSTOMER_LEDGER
UNION SELECT EVENT_ID,CUSTOMER_ID,EFFECTIVE_AT FROM L2_OBJECTS_LAB.M13_LAB.BATCH_EVENTS
) GROUP BY CUSTOMER_ID,EFFECTIVE_AT HAVING COUNT(*)>1
);
IF (bad>0) THEN RAISE invalid_batch; END IF;
INSERT INTO L2_OBJECTS_LAB.M13_LAB.CUSTOMER_LEDGER
SELECT b.EVENT_ID,b.CUSTOMER_ID,b.CITY,b.EFFECTIVE_AT,
L2_OBJECTS_LAB.M13_LAB.CUSTOMER_SK_SEQ.NEXTVAL
FROM (SELECT DISTINCT EVENT_ID,CUSTOMER_ID,CITY,EFFECTIVE_AT FROM L2_OBJECTS_LAB.M13_LAB.BATCH_EVENTS) b
WHERE NOT EXISTS (SELECT 1 FROM L2_OBJECTS_LAB.M13_LAB.CUSTOMER_LEDGER l WHERE l.EVENT_ID=b.EVENT_ID);
-- Rebuild only affected customers, but use their COMPLETE accepted history.
DELETE FROM L2_OBJECTS_LAB.M13_LAB.DIM_CUSTOMER
WHERE CUSTOMER_ID IN (SELECT CUSTOMER_ID FROM L2_OBJECTS_LAB.M13_LAB.BATCH_EVENTS);
INSERT INTO L2_OBJECTS_LAB.M13_LAB.DIM_CUSTOMER
SELECT CUSTOMER_SK,CUSTOMER_ID,CITY,EFFECTIVE_AT,NEXT_AT,(NEXT_AT IS NULL)
FROM (
SELECT l.*,LEAD(EFFECTIVE_AT) OVER(PARTITION BY CUSTOMER_ID ORDER BY EFFECTIVE_AT) AS NEXT_AT
FROM L2_OBJECTS_LAB.M13_LAB.CUSTOMER_LEDGER l
WHERE CUSTOMER_ID IN (SELECT CUSTOMER_ID FROM L2_OBJECTS_LAB.M13_LAB.BATCH_EVENTS)
);
UPDATE L2_OBJECTS_LAB.M13_LAB.PIPELINE_STATE SET LAST_DELIVERY=:hi;
INSERT INTO L2_OBJECTS_LAB.M13_LAB.RUN_AUDIT VALUES(:hi,:n,CURRENT_TIMESTAMP());
IF (FAIL_BEFORE_COMMIT) THEN RAISE forced_failure; END IF;
COMMIT; RETURN 'Batch committed';
EXCEPTION WHEN OTHER THEN
err := SQLERRM;
ROLLBACK;
-- Failure evidence is committed AFTER rolling back business work.
BEGIN TRANSACTION;
INSERT INTO L2_OBJECTS_LAB.M13_LAB.REJECT_LOG VALUES(CURRENT_TIMESTAMP(),:err);
COMMIT;
RAISE;
END;
$$;
CALL APPLY_CUSTOMER_BATCH(FALSE);
SELECT CUSTOMER_ID,CITY,VALID_FROM,VALID_TO,IS_CURRENT FROM DIM_CUSTOMER ORDER BY CUSTOMER_ID,VALID_FROM;What to expect and why
Three versions: C1 Pune [Jan 1, Mar 1), C1 Mumbai [Mar 1, open), C2 Delhi [Jan 1, open). Watermark 4; one successful audit with 4 deliveries. Surrogate values are not predetermined.
Check your understanding
Choose an answer, then check your reasoning. This is practice, not a scored test.
Try it yourself
Explain with the example: Can you advance the watermark before the dimension transaction commits?
Compare your reasoning
Commit data and acknowledgement together; otherwise recovery may skip uncommitted changes.