← All Exercises
Atomic Funds Transfer with a Transaction
advancedsql
Background
Money movement must be all-or-nothing. A transaction plus explicit row locks prevents partial debits, negative balances, and races between concurrent transfers.
Problem
Transfer 150 from account 1 to account 2 in a single transaction. Lock both rows, refuse the transfer when the source lacks funds or either account is missing, and leave balances unchanged on failure.
Input
A PostgreSQL accounts table with id integer PRIMARY KEY and balance numeric(12,2) NOT NULL CHECK (balance >= 0); the transfer is fixed at 150.00 from account 1 to account 2.
Output
On success both balances are updated and COMMIT persists them; on failure RAISE EXCEPTION aborts the transaction and no balance changes.
Sample tests
Sample 1
Input: accounts (1, 700.00) and (2, 300.00); transfer 150.00 from 1 to 2
Expected: account 1 = 550.00, account 2 = 450.00; total remains 1000.00
Sample 2
Input: account 1 balance 100.00, account 2 balance 300.00; transfer 150.00
Expected: ERROR: insufficient funds in account 1 (balance 100.00); balances remain 100.00 and 300.00
Your solution
Learning objective
Use explicit transactions, row-level locks, PL/pgSQL guards, and exception-driven rollback for atomic money movement.