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;
BEGIN TRANSACTION;starts a transaction. Writing onlyBEGIN;works too. In MySQL, this command is usually writtenSTART TRANSACTION;.- After
BEGIN, the changes from the twoUPDATEs aren't permanent yet. The connection that runs thoseUPDATEs already sees the new balances, but other connections (for example another program reading the same database) still see the old ones. COMMIT;saves every change sinceBEGINpermanently, all at once. The result is Budi $1,500 and Siti $1,500, exactly what the exercise asks for.ROLLBACK;is the opposite: it cancels every change sinceBEGIN, as if it never happened.
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:
- Atomicity (from atom, something that can't be split): all of the commands are saved, or none of them. This is the guarantee the transfer from Budi to Siti relies on.
- Consistency: after a transaction, the data still meets every rule, such as
max_balance. - Isolation: transactions running at the same time don't see each other's changes before
COMMIT. The isolation level says how strict that separation is. SQLite uses the strictest one (serializable: only one transaction may write at a time). MySQL's default isREPEATABLE READ, and PostgreSQL's default isREAD COMMITTED. - Durability: what has been committed is not lost, even if the server stops right after.
⚠️ A COMMIT at the wrong moment, a balance typed in by hand
COMMITeven though something failed. In SQLite, the commands that succeeded are still saved, so the transfer is only half done. If something failed, runROLLBACK.- Forgetting
COMMIT. Until you commit, the changes aren't permanent. If the connection closes, they are all cancelled. - Typing the final balance directly.
SET balance = 1500is only right if the starting balance is exactly what you assumed. Calculate it from the current balance:balance - 500. The exercise checks for this form. - Forgetting
WHERE.UPDATE accounts SET balance = balance - 500withoutWHEREtakes money from every account.
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.