Changing Data · Problem 112 of 118

Move Money Between Accounts

MediumChanging DataBank data

Move 5,000 cents from account 1 to account 2: subtract it from account 1 and add it to account 2. Do both changes in one transaction (BEGIN ... COMMIT), so that either both happen or neither.

Check query. After your statements run, this query is run on the changed data and its result is compared with the expected one:

SELECT account_id, balance_cents
FROM accounts
WHERE account_id IN (1, 2)
ORDER BY account_id;
Hint 1

BEGIN; then the two UPDATE statements, then COMMIT;.

Reference solution

BEGIN;
UPDATE accounts SET balance_cents = balance_cents - 5000 WHERE account_id = 1;
UPDATE accounts SET balance_cents = balance_cents + 5000 WHERE account_id = 2;
COMMIT;

A transfer is one business action made of two changes. If the system crashed after the first UPDATE, 5,000 cents would vanish. A transaction makes the two changes atomic: COMMIT saves both, ROLLBACK (or a crash before the commit) undoes both. Notice how the check query catches the half-done version: the total of the two accounts must stay the same, and the wrong answer loses money.