Skip to content

Transactions and ACID

Beginning of the lesson

Transactions and ACID

Group several statements into one all-or-nothing unit of work

Big Idea: A transaction is a group of SQL statements that the database treats as a single, indivisible unit: either all of them take effect, or none of them do. You open a transaction with START TRANSACTION, make your changes, and finish with COMMIT to save everything or ROLLBACK to throw it all away. This is how a bank can move money between two accounts without ever losing or inventing a single cent.
By the end you will be able to:
  • open, save and undo work with START TRANSACTION, COMMIT and ROLLBACK,
  • explain the four ACID guarantees using a bank transfer,
  • describe how autocommit wraps single statements automatically,
  • predict exactly what survives when a statement fails or a connection drops,
  • use SAVEPOINT to roll back only part of a transaction.

1. Our example schema: a tiny bank

Every example in this topic uses one small accounts table. Each row is a customer account with a name and a current balance. We use the InnoDB storage engine because in MySQL only InnoDB supports transactions (the older MyISAM engine ignores them). Create and fill the table once:

CREATE TABLE accounts (
    account_id INT PRIMARY KEY,
    owner      VARCHAR(40) NOT NULL,
    balance    DECIMAL(10,2) NOT NULL
) ENGINE = InnoDB;

INSERT INTO accounts (account_id, owner, balance) VALUES
    (1, 'Alice', 500.00),
    (2, 'Bob',   300.00),
    (3, 'Carol', 1000.00);

The starting data looks like this:

account_idownerbalance
1Alice500.00
2Bob300.00
3Carol1000.00

We use DECIMAL(10,2) for money on purpose: it stores exact values, unlike FLOAT, which would introduce rounding errors you never want near a bank balance.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers