SQLSQL
IntermediateLesson 10 of 15

Transactions & ACID – SQL

Executing multiple changes atomically – COMMIT, ROLLBACK, SAVEPOINT.

A transaction bundles several statements into one unit: either all take effect (COMMIT) or none (ROLLBACK). This is behind the acronym ACID: *Atomicity* (all or nothing), *Consistency* (constraints remain satisfied), *Isolation* (parallel transactions do not interfere), and *Durability* (after COMMIT it survives a crash).

-- Create an order: header and line items belong together
BEGIN;                                   -- MySQL: START TRANSACTION;
INSERT INTO bestellungen (kunde_id, datum, status) VALUES (5, '2024-04-10', 'offen');
INSERT INTO bestellpositionen (bestellung_id, produkt_id, menge)
VALUES ((SELECT MAX(id) FROM bestellungen), 4, 2);
COMMIT;

If something fails, you undo everything. In PostgreSQL, a transaction is "aborted" after an error and only accepts ROLLBACK; with SAVEPOINT you can roll back selectively to a marker.

BEGIN;
UPDATE produkte SET preis = preis * 2 WHERE kategorie = 'Bücher';
SAVEPOINT nach_preis;
DELETE FROM produkte WHERE id = 999;            -- nothing deleted, all fine
ROLLBACK TO nach_preis;                          -- discard only everything after the savepoint
ROLLBACK;                                        -- discard the price change as well

The classic bank transfer shows why atomicity matters: if the account is debited but the credit fails, money would have vanished.

BEGIN;
UPDATE konten SET saldo = saldo - 100 WHERE id = 1;
UPDATE konten SET saldo = saldo + 100 WHERE id = 2;
-- Check failed (e.g. saldo < 0)?  -> ROLLBACK;  otherwise:
COMMIT;
WarningWithout BEGIN, every statement runs in autocommit mode and becomes permanent immediately. And: DDL such as CREATE TABLE is transactional in PostgreSQL and SQLite, but in MySQL it triggers an implicit commit.
TipKeep transactions short: they hold locks. No user interaction and no long HTTP calls inside an open transaction.