Transactions in SQL
A transaction makes several statements land together or not at all.
BEGIN TRANSACTION;
UPDATE accounts
SET balance = balance - 250.00
WHERE id = 1;
UPDATE accounts
SET balance = balance + 250.00
WHERE id = 2;
INSERT INTO transfers (from_id, to_id, amount)
VALUES (1, 2, 250.00);
COMMIT;
How it works
BEGINopens it,COMMITmakes the work permanent.ROLLBACKthrows the whole batch away.- Money moving between accounts is the classic case.
Keywords and builtins used here
BEGINCOMMITINSERTINTOSETTRANSACTIONUPDATEVALUESWHERE
The run, in numbers
- Lines
- 14
- Characters to type
- 222
- Tokens
- 56
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 35 seconds.
Step 1 of 5 in Transactions, step 11 of 17 in Plans & performance.