Security & Architecture

Transaction Guide

A quick overview of safe data modifications using START TRANSACTION, COMMIT, ROLLBACK, and SAVEPOINT.

Why Transactions?

Transactions ensure that multiple SQL changes are treated as one indivisible unit: Either everything is successfully saved, or in case of an error, the previous state is completely restored.

Atomicity All or nothing. There are no "partial" updates.
Consistency Database rules (like constraints) are strictly maintained.
Isolation Concurrent accesses by other users do not interfere with each other.
Durability Once a COMMIT is executed, the data is stored permanently.

Typical Variants & Workflows

1 Safe Update + Commit

All statements belong to a single unit. Changes only become permanent upon executing COMMIT. If an error occurs beforehand, the transaction is rolled back. (Real-world scenario: Bank transfer. Either both debit and credit are saved, or neither.)

START TRANSACTION;
UPDATE account SET balance = balance - 100 WHERE account_id = 1;
UPDATE account SET balance = balance + 100 WHERE account_id = 2;
COMMIT;

2 Dry Run (Rollback as Default)

You first check the intermediate state within the open transaction and decide afterwards. Important: After a rollback, this transaction is closed. If you send ROLLBACK immediately in step 1, the decision is already made and nothing is saved permanently.

START TRANSACTION;
UPDATE orders SET status = 'done' WHERE order_id = 42;
SELECT * FROM orders WHERE order_id = 42;
ROLLBACK; -- Test first, then optionally send COMMIT in a new attempt

Editor Workflow (Separate Execution):

  1. Send START TRANSACTION + UPDATE + SELECT.
  2. Check the intermediate result.
  3. Only then manually send COMMIT (save) or ROLLBACK (discard).

3 Savepoint Workflow

A savepoint is a checkpoint within a running transaction. You can jump back to exactly this point without discarding the entire transaction. The name can be chosen freely.

START TRANSACTION;
SAVEPOINT before_step2;

UPDATE inventory SET stock = stock - 1 WHERE item_id = 7;

-- In case of an error in the step above: Jump back!
ROLLBACK TO SAVEPOINT before_step2;

-- Only COMMIT saves the remaining modifications.
COMMIT;

Important Notes

  • Transactions are only fully supported by engines like InnoDB.
  • DDL commands like CREATE, ALTER or DROP are often not rollback-able and automatically trigger a commit of the current transaction.
  • Keep transactions as short as possible to reduce database locks and waiting times for other users.
  • In critical workflows (e.g. inside PHP code), always explicitly check for errors (Exceptions) and catch them using a ROLLBACK.