Transactions — SQL

A transaction is a group of SQL commands that run as one unit: all of them are saved, or none of them is. BEGIN TRANSACTION; starts it, COMMIT; saves every…

You send money to a friend in your mobile banking app (your bank's app on your phone). Your balance goes down, the screen keeps loading, then the app shows an error. Your friend says nothing has arrived. Where did the money go?

A bank can't let that happen. Your balance goes down and your friend's balance goes up: those two things must happen together. The way to do it is a transaction: a group of SQL commands that run as one unit. There are only two possible results: all of the commands are saved, or none of them is. So money can't vanish on the way.

The accounts table

This is the accounts table from the exercise. The balance column holds each account's balance. The table also has one constraint from the previous lesson: a maximum balance of $2,000, like an e-wallet account that hasn't been upgraded. That rule is what will make one step fail.

CREATE TABLE accounts (
  id INTEGER PRIMARY KEY,
  name TEXT,
  balance REAL CONSTRAINT max_balance CHECK (balance <= 2000)
);
INSERT INTO accounts VALUES (1, 'Budi', 2000), (2, 'Siti', 1000);

CONSTRAINT max_balance only gives that CHECK a name, so its error message mentions the name max_balance.

A transfer from Budi to Siti takes two commands:

UPDATE accounts SET balance = balance - 1500 WHERE id = 1;  -- take from Budi
UPDATE accounts SET balance = balance + 1500 WHERE id = 2;  -- add to Siti

balance = balance - 1500 calculates the new balance from the current one. WHERE id = 1 makes sure only Budi's account changes.

Without a transaction: stuck halfway

Without a transaction, each command is saved permanently as soon as it finishes. Here is the order of events:

Step Budi Siti Total
Start 2,000 1,000 3,000
UPDATE Budi: succeeds, permanent at once 500 1,000 1,500
UPDATE Siti: CHECK constraint failed: max_balance 500 1,000 1,500

The second command would make Siti's balance $2,500. That is over the limit, so the second command is refused. But the first one is already saved. The two of them now have only $1,500 in total, so $1,500 is gone. The second command could fail for any reason: a broken rule, a server crash, or a lost connection to the database between the two commands.

BEGIN, COMMIT, ROLLBACK

These three commands wrap several commands into one transaction. In the code below, the transfer is $500, the amount the exercise asks for:

BEGIN TRANSACTION;
UPDATE accounts SET balance = balance - 500 WHERE id = 1;
UPDATE accounts SET balance = balance + 500 WHERE id = 2;
COMMIT;

When one step fails: ROLLBACK

Now the $1,500 transfer that failed above runs again, this time inside a transaction. The Budi and Siti columns show the balances that the connection running the transaction sees. The last column shows the balances that are already permanent:

Step Budi Siti What is permanent
BEGIN TRANSACTION; 2,000 1,000 2,000 and 1,000
UPDATE Budi: succeeds, not permanent yet 500 1,000 2,000 and 1,000
UPDATE Siti: CHECK constraint failed: max_balance 500 1,000 2,000 and 1,000
ROLLBACK; 2,000 1,000 2,000 and 1,000

Careful with the third row of the table: in SQLite, a command that fails only cancels itself. The transaction is still open, and the change to Budi's balance is still waiting. The next command decides whether that change is saved or cancelled. If you run COMMIT anyway, Budi's balance is saved as $500, and the money is still gone. MySQL works the same way as SQLite, but in PostgreSQL one error makes every later command fail with current transaction is aborted, commands ignored until end of transaction block, and a COMMIT there cancels everything instead. So the rule is: if everything went well, COMMIT. If something failed, ROLLBACK. In an app, this rule is written with try and catch (the way code catches an error). In Laravel (a PHP framework), DB::transaction(function () { ... }) runs BEGIN, then COMMIT if everything went well, or ROLLBACK if there was an error.

📌 ACID

The four guarantees a transaction gives, shortened to ACID:

⚠️ A COMMIT at the wrong moment, a balance typed in by hand

TL;DR: A transaction is a group of SQL commands that run as one unit: all of them are saved, or none of them is. BEGIN TRANSACTION; starts it, COMMIT; saves every change permanently at once, and ROLLBACK; cancels everything. Without a transaction, a command that already ran stays saved even if the next one fails, so money can vanish in the middle of a transfer. Inside a transaction in SQLite, a failing command only cancels itself, so when there is an error, you are the one who must run ROLLBACK. Calculate balances from the current value (balance - 500, where balance is the balance column), and always use WHERE.

⚡ Two commands, one transfer

Meaning: A transfer of money from Budi to Siti needs two UPDATE commands: take from Budi's balance, then add to Siti's. Without a transaction (a group of commands that run as one unit), each command is saved permanently as soon as it finishes.

⚡ Stuck halfway

Guess first: Budi sends $1,500 to Siti with no transaction. Budi's UPDATE succeeds, then Siti's UPDATE is refused. Does Budi get his money back?

No. The change to Budi's balance is already saved, so $1,500 vanishes on the way.

Meaning: The second command could fail for any reason: a broken rule, a server crash, or a lost connection to the database.

⚡ BEGIN and COMMIT

Write:

BEGIN TRANSACTION;
UPDATE accounts SET balance = balance - 500 WHERE id = 1;
UPDATE accounts SET balance = balance + 500 WHERE id = 2;
COMMIT;

Meaning: BEGIN TRANSACTION; starts a transaction. After it, the changes from the two UPDATEs aren't permanent yet. COMMIT; saves them all at once. Calculate the balance (balance) from the current value (balance - 500), and always use WHERE, so only one account changes.

The exercise checks that balances are calculated as balance - 500, not typed in.

⚡ An error? ROLLBACK

Meaning: Inside a transaction in SQLite, a failing command only cancels itself. The transaction stays open: the changes that succeeded are still waiting for COMMIT or ROLLBACK. If everything went well, run COMMIT. If something failed, run ROLLBACK: it cancels every change since BEGIN.

What you will learn