← Back to PostgreSQL Course | Chapter 10: Advanced Features | Lesson 5 of 7

Transactions (BEGIN/COMMIT/ROLLBACK)

A transaction groups statements so they all succeed together or are all undone.
Syntax
sql
BEGIN;
-- statements
COMMIT;

BEGIN;
-- statements
ROLLBACK;

Transactions (BEGIN/COMMIT/ROLLBACK)

BEGIN starts a transaction, COMMIT makes its changes permanent and ROLLBACK discards them. PostgreSQL provides ACID guarantees, and DDL statements are transactional too.

SAVEPOINT allows partial rollbacks. Isolation levels (read committed by default, repeatable read, serializable) control what concurrent transactions see.

Note: Every statement outside BEGIN is its own automatic transaction.

Example: Transactions (BEGIN/COMMIT/ROLLBACK)

sql
CREATE TABLE accounts (id INTEGER PRIMARY KEY, owner TEXT, balance INTEGER);
INSERT INTO accounts VALUES (1, 'Ada', 100), (2, 'Bob', 50);
BEGIN;
UPDATE accounts SET balance = balance - 30 WHERE id = 1;
UPDATE accounts SET balance = balance + 30 WHERE id = 2;
COMMIT;
SELECT owner, balance FROM accounts ORDER BY id;
BEGIN;
UPDATE accounts SET balance = 0 WHERE id = 1;
ROLLBACK;
SELECT owner, balance FROM accounts ORDER BY id;

-- Output:
-- owner | balance
-- Ada | 70
-- Bob | 80
-- owner | balance
-- Ada | 70
-- Bob | 80
Related Topics
Common Mistakes
  1. Leaving transactions open for a long time
  2. Forgetting to roll back after an error
  3. Assuming autocommit works inside BEGIN
Chapter Summary
  • BEGIN, COMMIT, ROLLBACK
  • All or nothing
  • ACID guarantees
  • Isolation levels control concurrency
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.