typestar

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

  1. BEGIN opens it, COMMIT makes the work permanent.
  2. ROLLBACK throws the whole batch away.
  3. Money moving between accounts is the classic case.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 5 in Transactions, step 11 of 17 in Plans & performance.

← Previous Next →