Transactions
Group multiple statements into an atomic unit of work.
BEGIN/COMMIT/ROLLBACK
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT; -- or ROLLBACK on error
Clients often expose transaction blocks/helpers; ensure errors trigger rollback.
ACID properties
- Atomicity: all or nothing
- Consistency: constraints hold before/after
- Isolation: concurrent transactions don’t interfere (see isolation levels)
- Durability: committed changes persist
Savepoints
BEGIN;
SAVEPOINT sp1;
UPDATE orders SET status = 'paid' WHERE id = 10;
ROLLBACK TO SAVEPOINT sp1; -- undo partial work
COMMIT;
Retry patterns
Detect serialization conflicts and retry idempotent transactions.
Best practices
- Keep transactions short to reduce contention
- Touch rows in a consistent order to avoid deadlocks
- Enforce business invariants with constraints and unique indexes
Summary
- Use transactions for atomic changes; savepoints for partial rollback
- Design for retries under high concurrency