← Back to SQL, page 12

sql-0223 · Easy fresher

What is a transaction, and what do COMMIT and ROLLBACK do?

A transaction groups statements into one unit that either takes effect completely or not at all. COMMIT makes the changes permanent and visible to others; ROLLBACK discards every change made since BEGIN. Without an explicit BEGIN, most engines run each statement in its own transaction (autocommit).

Full answer
sql
CREATE TABLE accounts (id INTEGER PRIMARY KEY, owner TEXT, balance INTEGER NOT NULL CHECK (balance >= 0));
INSERT INTO accounts VALUES (1, 'Ana', 100), (2, 'Bilal', 50);
sql
BEGIN;
UPDATE accounts SET balance = balance - 30 WHERE id = 1;
UPDATE accounts SET balance = balance + 30 WHERE id = 2;
ROLLBACK;
SELECT id, balance FROM accounts ORDER BY id;
idbalance
1100
250

The transfer was applied inside the transaction and then rolled back, so both balances are back to their starting values. Replacing ROLLBACK with COMMIT would keep both updates together.

Grouping matters because a transfer is two writes. If the program crashed between them in autocommit mode, 30 would leave Ana's account and never arrive in Bilal's. Inside a transaction, a crash before COMMIT leaves neither change, because the engine undoes incomplete transactions on recovery.

Keep transactions short. An open transaction holds locks (or, in MVCC engines, old row versions) until it ends.

sql
CREATE TABLE accounts (id INTEGER PRIMARY KEY, owner TEXT, balance INTEGER NOT NULL CHECK (balance >= 0));
INSERT INTO accounts VALUES (1, 'Ana', 100), (2, 'Bilal', 50);

BEGIN;
UPDATE accounts SET balance = balance - 30 WHERE id = 1;
UPDATE accounts SET balance = balance + 30 WHERE id = 2;
ROLLBACK;
SELECT id, balance FROM accounts ORDER BY id;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • A transaction is all-or-nothing
  • COMMIT makes changes permanent
  • ROLLBACK undoes changes since BEGIN
  • Autocommit wraps each statement separately

Common mistakes

  • Running related writes in autocommit mode
  • Leaving transactions open while waiting for user input

Follow-ups

  • What does ACID stand for?
  • What happens to an open transaction if the connection drops?

Tips

  • Use a money transfer as the example