Databases in practice

Keep related changes together with transactions

Wrap related statements in a transaction so they all succeed or all roll back.

8 minute lesson

~~~

A money transfer changes at least two balances. Saving only one change would leave the data inconsistent.

Treat the transfer as one unit:

BEGIN;

UPDATE accounts
SET balance_cents = balance_cents - 5000
WHERE id = 10;

UPDATE accounts
SET balance_cents = balance_cents + 5000
WHERE id = 20;

COMMIT;

COMMIT makes both changes durable. If a statement fails, the application should issue ROLLBACK so neither change remains:

ROLLBACK;

Atomicity does not make incorrect business logic correct. The first update must also prove that account 10 exists and has enough funds. You might enforce a non-negative balance with a constraint and check the affected-row count, or lock and read the account using the concurrency features of your database.

Application code must execute every statement on the same database connection. Sending BEGIN on one pooled connection and the updates on another does not create one transaction.

Keep transactions short. Do not wait for an HTTP request, user input, or a slow unrelated job while holding database locks. Concurrent transactions can block each other or deadlock. Applications commonly retry the complete transaction after a transient deadlock—not just the final statement—because the database rolled back the whole unit.

Transaction and locking syntax differs between database systems, but the boundary should always match one business operation.

Your action: run a two-statement transaction against test data, deliberately make the second statement fail, issue ROLLBACK, and verify with a SELECT that the first change did not survive.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →