Module 10 · Lesson 8 of 8Detailed study · about 20 min

Lab: transform a batch and roll back on failure

Combine a reusable calculation with a procedure that owns its transaction, validates inputs and re-raises failures after rollback.

Understand the idea

The lab loads a two-row source into a target using M10_NET from the function lesson. The procedure validates a discount rate, clears its dedicated target and writes transformed rows in one transaction.

Key ideas in simple English
ConceptWhat it means
Custom exceptionReports a deliberate business validation failure.
EXCEPTION handlerHandles an error path explicitly.
ROLLBACKUndoes the procedure’s uncommitted writes.
RAISEReports failure instead of pretending the operation succeeded.

A concrete example

Run once with an idle session and the intended schema. Source has two rows; target starts empty. M10_NET must already exist.

Remember: Commit and rollback belong to the complete business operation; report failure to the caller after cleanup.

Explain it step by step · full theory

Understand the idea

The lab loads a two-row source into a target using M10_NET from the function lesson. The procedure validates a discount rate, clears its dedicated target and writes transformed rows in one transaction.

The transaction starts and finishes within this procedure. Call it outside an existing explicit transaction. Do not put CREATE or other DDL inside its transactional body: implicit commits can break the intended boundary.

Follow the example

A test-only Boolean argument raises a controlled error after the DELETE. The handler rolls back and re-raises, so a failed call leaves the previously committed target intact. This is deliberate failure injection for learning, not an application API design.

The client may stop on the expected error. Run the verification SELECT separately afterward. Do not swallow every exception and return a success message; the caller must be able to distinguish a failed operation.

Words used in this lesson
Custom exception
Reports a deliberate business validation failure.
EXCEPTION handler
Handles an error path explicitly.
ROLLBACK
Undoes the procedure’s uncommitted writes.
RAISE
Reports failure instead of pretending the operation succeeded.

See how it works

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

Open the interactive explanation
Interactive explainer1 / 3

Lab: transform a batch and roll back on failure

Input
Business rule

Start with the requirement

Combine a reusable calculation with a procedure that owns its transaction, validates inputs and re-raises failures after rollback.

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 requirement

    Combine a reusable calculation with a procedure that owns its transaction, validates inputs and re-raises failures after rollback.

  2. Apply the rule

    The lab loads a two-row source into a target using M10_NET from the function lesson. The procedure validates a discount rate, clears its dedicated target and writes transformed rows in one transaction.

  3. Explain the result

    Commit and rollback belong to the complete business operation; report failure to the caller after cleanup.

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 practice in an authorized Snowflake learning account. Run lesson 1 setup first and select L2_OBJECTS_LAB.M10_LAB and your authorized warehouse in each session. Use fresh object names; do not replace existing objects. Read whole scripting blocks before running them. The website does not execute commands.

Prepare the dedicated lab tables

SQL · example
CREATE TABLE M10_SOURCE (ID NUMBER, AMOUNT NUMBER(12,2));
INSERT INTO M10_SOURCE VALUES (1,100),(2,80);
CREATE TABLE M10_TARGET (ID NUMBER, NET_AMOUNT NUMBER(12,2));

What to expect and why

Run once with an idle session and the intended schema. Source has two rows; target starts empty. M10_NET must already exist.

Create the transaction-owning procedure

SQL · example
CREATE PROCEDURE M10_APPLY(RATE NUMBER(5,4), FAIL_AFTER_DELETE BOOLEAN)
RETURNS VARCHAR LANGUAGE SQL EXECUTE AS CALLER
AS $$
DECLARE
 invalid_rate EXCEPTION (-20001, 'Rate must be between zero and one');
 simulated_failure EXCEPTION (-20002, 'Practice failure after delete');
BEGIN
 BEGIN TRANSACTION;
 IF (RATE IS NULL OR RATE < 0 OR RATE > 1) THEN
   RAISE invalid_rate;
 END IF;
 DELETE FROM L2_OBJECTS_LAB.M10_LAB.M10_TARGET;
 IF (FAIL_AFTER_DELETE) THEN
   RAISE simulated_failure;
 END IF;
 INSERT INTO L2_OBJECTS_LAB.M10_LAB.M10_TARGET
 SELECT ID, L2_OBJECTS_LAB.M10_LAB.M10_NET(AMOUNT,:RATE)
 FROM L2_OBJECTS_LAB.M10_LAB.M10_SOURCE;
 COMMIT;
 RETURN 'Batch committed';
EXCEPTION
 WHEN OTHER THEN
   ROLLBACK;
   RAISE;
END;
$$;

What to expect and why

The procedure commits both the target replacement and transformed rows, or rolls them back on a handled failure. Source rows remain unchanged.

Successful call

SQL · example
CALL M10_APPLY(0.10,FALSE);
SELECT * FROM M10_TARGET ORDER BY ID;

What to expect and why

Returns Batch committed. Target rows are 1/90.00 and 2/72.00, totaling 162.

Intentional failure — run verification separately

SQL · example
CALL M10_APPLY(0.20,TRUE);
-- After the expected error, run this SELECT separately:
SELECT * FROM M10_TARGET ORDER BY ID;

What to expect and why

The call raises the practice error after deleting rows inside the transaction. Rollback restores the prior 90.00 and 72.00 rows. They must not disappear or change to 80/64.

Reject an invalid rate

SQL · example
CALL M10_APPLY(2,FALSE);
-- After the expected error:
SELECT COUNT(*) AS ROWS_REMAINING, SUM(NET_AMOUNT) AS TOTAL FROM M10_TARGET;

What to expect and why

The rate validation fails. Expected retained state is 2 rows totaling 162 after the earlier successful call.

Check your understanding

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

What should remain after the intentional failed call?

Try it yourself

Run the successful call with 0.25 after investigating the failure. Predict the target.

Compare your reasoning

Rows become 1/75.00 and 2/60.00, totaling 135. Run only outside an unrelated transaction.

Official sources and curriculum

Module 10 · See module scope