Course topics

By WebNest Studio Engineering Team

Database and SQL Tutorial

Database Transactions

A transaction is a group of one or more SQL statements that are executed as a single, indivisible unit of work. Either every statement in the transaction succeeds and its changes are saved permanently, or — if anything goes wrong — none of the statements take effect and the database is left exactly as it was before the transaction started.

This matters whenever an operation involves multiple related changes that must happen together. If only some of the changes were applied and the rest failed silently, the database would be left in an inconsistent state that doesn't correspond to any valid real-world outcome.

Why it matters

Moving money between two accounts takes two updates, and a crash between them would destroy money. A transaction makes the two updates a single unit: both happen or neither does. Any operation that changes more than one row in a way that must stay consistent needs one.

BEGIN, COMMIT, and ROLLBACK

A transaction is controlled with three commands. BEGIN (or START TRANSACTION) marks the start of a transaction block. COMMIT saves all changes made since BEGIN permanently to the database. ROLLBACK discards all changes made since BEGIN, as if none of the statements ever ran. Many databases also run every individual statement in its own implicit transaction by default (called "autocommit"), and BEGIN/COMMIT/ROLLBACK are how you opt out of that to group several statements together.

  • BEGIN / START TRANSACTION — opens a transaction block.
  • COMMIT — makes all changes in the transaction permanent and visible to other connections.
  • ROLLBACK — undoes all changes made since BEGIN, restoring the prior state.

Why Multi-Statement Operations Need Atomicity

Consider transferring $100 from Account A to Account B. This requires two separate statements: subtract $100 from A, and add $100 to B. If the subtraction succeeds but the server crashes, the network drops, or a constraint fails before the addition runs, $100 has simply vanished from the system — it left A but never reached B. Wrapping both statements in a transaction guarantees that either both changes happen together or neither does, so the money is never lost or duplicated.

A Concrete Bank Transfer Example

The pattern below is the classic illustration of why transactions exist: two UPDATE statements that must rise or fall together, with an explicit ROLLBACK if a business rule (insufficient funds) is violated partway through.

Examples

A safe bank transfer using an explicit transaction

SQL
BEGIN;

UPDATE accounts
SET balance = balance - 100
WHERE account_id = 'A' AND balance >= 100;

UPDATE accounts
SET balance = balance + 100
WHERE account_id = 'B';

COMMIT;
Output
UPDATE 1
UPDATE 1
COMMIT
(Account A is now $100 lower, Account B is $100 higher — both changes are visible together, or neither is.)

Rolling back when a business rule fails mid-transaction

SQL
BEGIN;

UPDATE accounts SET balance = balance - 500 WHERE account_id = 'A';
-- Application checks the new balance and finds it went negative,
-- which violates the "no overdraft" business rule.

ROLLBACK;

-- Account A's balance is exactly what it was before BEGIN.
SELECT balance FROM accounts WHERE account_id = 'A';
Output
ROLLBACK
balance: 250.00   -- unchanged, as if the UPDATE never ran

Common Mistakes

  • Forgetting to COMMIT, leaving a transaction open and holding locks that block other connections until it times out or the session closes.
  • Assuming a ROLLBACK undoes changes already committed by an earlier, separate transaction — ROLLBACK only affects statements since the current BEGIN.
  • Doing the balance check in application code after the UPDATE without re-verifying inside the same transaction, allowing a race condition if two transfers run concurrently.
  • Wrapping a single, independent statement in BEGIN/COMMIT for no reason — most databases already treat a lone statement as its own atomic transaction.

Exercise

Transfer 30 from account A to account B inside a transaction and commit it. Then start a second transaction that moves 500 from A to B, and roll it back because A cannot afford it. Finally list the balances.

Expected output: name | balance, A | 70, B | 80 (one per line)

SQL · starter code
CREATE TABLE accounts (name TEXT PRIMARY KEY, balance INTEGER);
INSERT INTO accounts (name, balance) VALUES ('A', 100), ('B', 50);

-- TODO: a transaction that moves 30 from A to B, then commits

-- TODO: a transaction that moves 500 from A to B, then rolls back

SELECT name, balance FROM accounts ORDER BY name;
Show hints
  • A transaction starts with BEGIN and ends with COMMIT or ROLLBACK.
  • Each transfer is two UPDATE statements: one subtracting from A and one adding to B.
Show solution
SQL · solution
CREATE TABLE accounts (name TEXT PRIMARY KEY, balance INTEGER);
INSERT INTO accounts (name, balance) VALUES ('A', 100), ('B', 50);

BEGIN;
UPDATE accounts SET balance = balance - 30 WHERE name = 'A';
UPDATE accounts SET balance = balance + 30 WHERE name = 'B';
COMMIT;

BEGIN;
UPDATE accounts SET balance = balance - 500 WHERE name = 'A';
UPDATE accounts SET balance = balance + 500 WHERE name = 'B';
ROLLBACK;

SELECT name, balance FROM accounts ORDER BY name;

Quick quiz

1. What does ROLLBACK do?

  • A. Saves the changes permanently
  • B. Deletes the table
  • C. Undoes every change made since the transaction began
  • D. Restarts the database
Show answer

C. The data returns to the state it was in at BEGIN.

2. When do the changes of a transaction become permanent and visible to others?

  • A. At COMMIT
  • B. As each statement runs
  • C. When the connection closes
  • D. At BEGIN
Show answer

A. Until then they can still be rolled back.

3. A connection is lost in the middle of a transaction, before COMMIT. What happens to its changes?

  • A. They are committed
  • B. Half of them are kept
  • C. The table is locked for ever
  • D. They are rolled back
Show answer

D. An unfinished transaction is never applied.

Interview questions

What is a transaction?

Show answer

A transaction is a sequence of statements that the database treats as one unit of work. Either all of them take effect, when the transaction is committed, or none do, when it is rolled back. It is opened with BEGIN and closed with COMMIT or ROLLBACK. Transactions keep data consistent when an operation needs several changes that must succeed together, such as a transfer or placing an order.

What is a savepoint?

Show answer

A savepoint is a named marker inside a transaction. SAVEPOINT name creates it, and ROLLBACK TO name undoes everything done after it while keeping the earlier work and leaving the transaction open. It allows part of a transaction to be retried or abandoned without giving up the whole thing.

Key Points to Remember

  • A transaction groups multiple statements so they either all succeed (COMMIT) or all fail together (ROLLBACK).
  • BEGIN starts a transaction block; COMMIT makes its changes permanent; ROLLBACK discards them entirely.
  • Multi-step operations like a bank transfer need transactions specifically to avoid a partial, inconsistent outcome (money leaving one account without arriving in another).

Practice in the playground

Write and run your own code for this topic, or start from the exercise or an example. Runs your SQL on SQLite in your browser. Standard SQL works; a few features that exist only in PostgreSQL or MySQL do not. Your code for each topic is kept in this browser.

Run the examples

Change an input, predict the result, then compare it with the output. Explain why the result changes.

These examples need a project environment on your computer, so they can be copied but not run here. Codelab runs Python, FastAPI backends with SQLite, plain Java 17 and HTML/CSS/JavaScript.

WebNest Studio

Written by

WebNest Studio Engineering Team

Practical lessons from developers working with Java, Python, React, databases and production systems.

Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering