1.BEGIN, COMMIT and ROLLBACK
BEGIN starts a transaction block, grouping every following statement into one all-or-nothing unit. COMMIT makes every change in that block permanent and visible to other transactions. ROLLBACK discards every change made since BEGIN, as if none of it ever happened.
Key features
- BEGIN opens a transaction block; every statement after it is part of the same all-or-nothing unit until COMMIT or ROLLBACK
- COMMIT makes every change since BEGIN permanent and visible to other sessions, in a single atomic step
- ROLLBACK discards every change since BEGIN, restoring the state as if the block never ran
- A transaction block that hits an unhandled error is left in an "aborted" state — every statement inside it is discarded, and only ROLLBACK (not COMMIT) can close it out
- END is a synonym for COMMIT in PostgreSQL
BEGIN / COMMIT / ROLLBACK
- No transaction (start)
- → Transaction block open when BEGIN
- Transaction block open
- → Committed when COMMIT
- → Rolled back when ROLLBACK
- Committed (end)
- Rolled back (end)
Command
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE name = 'Alice';
UPDATE accounts SET balance = balance + 100 WHERE name = 'Bob';
COMMIT; -- both updates become permanent together, or...
-- ROLLBACK; -- ...neither doesBEGIN opens an all-or-nothing block; COMMIT makes every change since BEGIN permanent at once; ROLLBACK discards every change since BEGIN, not just the last statement. Nothing is durable until COMMIT actually runs.