smartyfy.mrindigi.com

Databases & SQL Master Course — 057. Transactions with BEGIN COMMIT and ROLLBACK

Lesson 057 Transactions with BEGIN COMMIT and ROLLBACK

Prerequisites and objectives

You can target a write and inspect its results. Now you will group related writes into one deliberate unit, distinguish COMMIT from ROLLBACK, and recognize why a statement error is not necessarily a complete transaction rollback. The example moves fictional stock between two storage bins.

Create the practice fixture

Use a fresh in-memory or disposable SQLite database. Bin A contains twelve units and bin B contains three. The total is fifteen. Run each exercise from this fixture; the one explicitly labeled COMMIT persists only within that disposable exercise database. Recreate the fixture in a new database before trying another exercise.

CREATE TABLE bins (
 bin_code TEXT PRIMARY KEY NOT NULL,
 units INTEGER NOT NULL CHECK(units>=0)
);
INSERT INTO bins VALUES ('A',12),('B',3);

Define the business unit of work

A transfer of four units consists of two row changes: subtract four from A and add four to B. The business operation is complete only when both changes agree. Running unrelated autocommitted statements risks leaving a halfway state if the second operation fails. A transaction supplies a boundary around the pair, but the SQL must still encode the correct business rule.

Write the expected final state before writing the mutation: A should become eight, B should become seven, and the sum should remain fifteen. These checks serve different purposes. A preserved total alone would not catch moving stock to the wrong bin. Correct individual balances without the right transaction boundary would not protect a partially executed workflow.

BEGIN;
UPDATE bins SET units=units-4 WHERE bin_code='A' AND units>=4;
UPDATE bins SET units=units+4 WHERE bin_code='B';
SELECT bin_code,units FROM bins ORDER BY bin_code;
SELECT SUM(units) FROM bins;
ROLLBACK;
SELECT bin_code,units FROM bins ORDER BY bin_code;

BEGIN opens the explicit boundary. The two updates execute inside it, and the same connection can inspect the tentative result. ROLLBACK discards both changes. In a real application, the caller must verify each expected affected-row count before continuing. If the debit matches zero rows, blindly applying the credit would create stock.

A BEGIN boundary groups a debit of four units from bin A, 12 to 8, and credit to bin B, 3 to 7. Both changes should affect one row and keep total stock 15. Separate alternative endings show COMMIT accepting 8 and 7, or ROLLBACK restoring 12 and 3. A failed debit guard requires stopping before credit.
A transaction groups the writes, while explicit outcome checks establish whether the intended transfer succeeded. Choose one ending for the complete unit. Open full-size diagram

Choose the ending deliberately

COMMIT accepts the transaction’s changes. ROLLBACK abandons them. After a successful commit, a later rollback cannot rewind that completed transaction; recovery requires a separately designed compensating operation or restore process. During learning, use rollback by default and perform committed examples only in fresh disposable databases.

SQLite automatically uses transactions even when you do not type BEGIN. An explicit boundary changes how several statements are grouped. Client libraries and SQL editors may add their own transaction management, so check whether a transaction is already active before starting another. SQLite BEGIN transactions do not nest; savepoints handle nested rollback boundaries in the next lesson.

Handle failure as a workflow decision

The stock CHECK rejects a negative balance. With the ordinary default constraint behavior, the failing statement is undone while earlier successful statements can remain pending. Therefore an error message is a signal to inspect or explicitly abandon the whole operation, not evidence that every earlier write disappeared.

This lesson uses one connection and does not demonstrate competing writers. SQLite permits one simultaneous writer, and BEGIN IMMEDIATE can request the write transaction earlier; busy handling and concurrency tests come later. Do not leave a transaction open while waiting for a person to approve an unrelated decision. Prepare the plan first, then keep the actual write window short.

Four worked exercises

Exercise 1

Rehearse moving two units from B to A and verify both bins.

Worked solution
BEGIN;
UPDATE bins SET units=units-2 WHERE bin_code='B' AND units>=2;
UPDATE bins SET units=units+2 WHERE bin_code='A';
SELECT bin_code,units FROM bins ORDER BY bin_code;
ROLLBACK;

The directional check matters: A increases and B decreases. Both targeted statements affect one row in this fixture. The final rollback restores twelve and three, preserving a repeatable starting point for the remaining examples.

Exercise 2

Commit a one-unit transfer from A to B in a fresh disposable fixture.

Worked solution
BEGIN;
UPDATE bins SET units=units-1 WHERE bin_code='A';
UPDATE bins SET units=units+1 WHERE bin_code='B';
COMMIT;
SELECT bin_code,units FROM bins ORDER BY bin_code;

The query after COMMIT sees eleven and four. This example intentionally retains those values only in its isolated practice database. Do not run subsequent exercises against that altered fixture without creating a fresh database.

Exercise 3

Show why a CHECK error should not be treated as automatic rollback of earlier work.

Worked solution
BEGIN;
UPDATE bins SET units=units+1 WHERE bin_code='A';
UPDATE bins SET units=-1 WHERE bin_code='B';
SELECT bin_code,units FROM bins ORDER BY bin_code;
ROLLBACK;

Run the failing statement separately if the editor stops a script on error, then inspect and rollback. A is temporarily thirteen because its earlier update remains pending. The application should abandon this incomplete business operation.

Exercise 4

Preview a transfer of twenty units from A. Demonstrate the guard and choose the safe response.

Worked solution
BEGIN;
UPDATE bins SET units=units-20 WHERE bin_code='A' AND units>=20;
SELECT bin_code,units FROM bins ORDER BY bin_code;
ROLLBACK;

The debit affects zero rows, so no credit is attempted. The available stock fails the stated precondition. Transaction boundaries protect a group, while outcome checks decide whether the intended group actually succeeded.

Knowledge check

Question 1

What is the intended transfer unit?

  1. Only the source-bin update
  2. Both debit and credit together
  3. Only the destination-bin update
  4. Each SELECT independently
Answer and explanation

B. The business invariant spans two writes, so their outcomes must be accepted or abandoned together.

Question 2

What does a default CHECK failure guarantee here?

  1. Every previous statement is committed
  2. Every previous statement is necessarily rolled back
  3. The next statement is automatically skipped by SQLite
  4. The failing statement is rejected
Answer and explanation

D. Earlier successful work can remain in the transaction, so the caller must manage the failure path.

Question 3

What should happen after a guarded debit affects zero rows?

  1. Credit anyway because BEGIN ensures correctness
  2. Remove the guard and retry the debit blindly
  3. Stop before crediting and abandon the operation
  4. Commit the credit and retry only the debit
Answer and explanation

C. Zero rows means the intended debit did not occur.

Question 4

What can ROLLBACK undo?

  1. Changes in the active transaction
  2. Any transaction committed yesterday
  3. External messages already sent
  4. Every change in another connection
Answer and explanation

A. Rollback applies to changes in its active transaction, not committed work or effects outside that transaction.

Question 5

Why verify individual bin balances as well as the total?

  1. SUM cannot see changes made inside an active transaction
  2. A conserved total can hide a wrong destination
  3. Each UPDATE automatically verifies the intended destination
  4. COMMIT checks the transfer’s business meaning
Answer and explanation

B. Conservation is necessary here but not sufficient to prove the intended transfer.

Pitfalls and summary

A transaction does not repair a wrong predicate, detect a missing business check, or reverse an external message. Plan the expected row counts and invariants, execute a short bounded operation, inspect the result, and choose one ending. Treat an uncertain error path as a reason to stop and establish transaction state before attempting another write.

SQLite behavior and references

Examples were checked with SQLite 3.53.1 on 10 October 2026. Use a SQLite SQL editor; Python is not a prerequisite. Verify dialect-specific functions, comparison rules, and numeric behavior before moving the examples to another engine.

Primary references