PostgreSQL Transactions
A transaction groups several statements into one unit of work that either succeeds completely or has no effect at all. The classic example is a bank transfer: taking money from one account and adding it to another must never happen only halfway.
PostgreSQL transactions are ACID:
| Letter | Property | Meaning |
|---|---|---|
| A | Atomicity | all statements take effect, or none do |
| C | Consistency | constraints hold before and after |
| I | Isolation | concurrent transactions don't see each other's half-done work |
| D | Durability | once committed, data survives a crash |
BEGIN, COMMIT and ROLLBACK
Without BEGIN, every statement is its own transaction and is committed immediately (autocommit). BEGIN starts a transaction, COMMIT makes its changes permanent and ROLLBACK throws them away:
BEGIN;
UPDATE books SET stock = stock - 1 WHERE id = 1;
INSERT INTO orders (customer_id, order_date, status) VALUES (1, '2025-01-10', 'pending');
COMMIT;
SELECT stock FROM books WHERE id = 1;
SELECT count(*) AS orders FROM orders;BEGIN
UPDATE 1
INSERT 0 1
COMMIT
stock
-------
11
(1 row)
orders
--------
21
(1 row)
Now the same with ROLLBACK. Inside the transaction the change is visible, afterwards it is gone:
BEGIN;
DELETE FROM order_items;
SELECT count(*) AS items_inside_transaction FROM order_items;
ROLLBACK;
SELECT count(*) AS items_after_rollback FROM order_items;BEGIN
DELETE 34
items_inside_transaction
--------------------------
0
(1 row)
ROLLBACK
items_after_rollback
----------------------
34
(1 row)
Tip: Before a risky
UPDATEorDELETEon a real database, typeBEGIN;first. Check the result with aSELECT, thenCOMMITorROLLBACK.
Errors abort the transaction
If a statement inside a transaction fails, PostgreSQL marks the whole transaction as failed. Every following statement is refused until you end it, and even COMMIT then performs a rollback:
BEGIN;
UPDATE books SET stock = stock + 10 WHERE id = 2;
UPDATE books SET price = -1 WHERE id = 2;
SELECT stock FROM books WHERE id = 2;
COMMIT;
SELECT stock FROM books WHERE id = 2;BEGIN
UPDATE 1
ERROR: new row for relation "books" violates check constraint "books_price_check"
DETAIL: Failing row contains (2, Harbor Lights, 1, 1, -1.00, 10, 2015-06-02, {family,sea}, {"pages": 248, "format": "paperback", "language": "en"}).
ERROR: current transaction is aborted, commands ignored until end of transaction block
ROLLBACK
stock
-------
0
(1 row)
The COMMIT answered ROLLBACK: the first, successful update was undone too. That is atomicity in action.
Savepoints
A savepoint is a bookmark inside a transaction. ROLLBACK TO SAVEPOINT undoes only the work after the bookmark, and also recovers from an error without losing everything:
BEGIN;
INSERT INTO categories (name) VALUES ('Travel');
SAVEPOINT before_art;
INSERT INTO categories (name) VALUES ('Art');
INSERT INTO categories (name) VALUES ('Fiction'); -- duplicate: fails
ROLLBACK TO SAVEPOINT before_art;
INSERT INTO categories (name) VALUES ('Comics');
COMMIT;
SELECT id, name FROM categories WHERE id > 7 ORDER BY id;BEGIN
INSERT 0 1
SAVEPOINT
INSERT 0 1
ERROR: duplicate key value violates unique constraint "categories_name_key"
DETAIL: Key (name)=(Fiction) already exists.
ROLLBACK
INSERT 0 1
COMMIT
id | name
----+--------
8 | Travel
11 | Comics
(2 rows)
'Travel' and 'Comics' were committed; 'Art' was rolled back with the savepoint. Notice the ids: 9 and 10 were taken by 'Art' and by the failed 'Fiction' insert, and sequence numbers are never handed out twice.
A transfer done right
A safer version of "move stock between two warehouses" checks the rule with a constraint and does both changes in one transaction:
CREATE TABLE warehouse (name text PRIMARY KEY, copies integer NOT NULL CHECK (copies >= 0));
INSERT INTO warehouse VALUES ('north', 5), ('south', 2);
BEGIN;
UPDATE warehouse SET copies = copies - 8 WHERE name = 'north';
UPDATE warehouse SET copies = copies + 8 WHERE name = 'south';
COMMIT;
SELECT * FROM warehouse ORDER BY name;CREATE TABLE
INSERT 0 2
BEGIN
ERROR: new row for relation "warehouse" violates check constraint "warehouse_copies_check"
DETAIL: Failing row contains (north, -3).
ERROR: current transaction is aborted, commands ignored until end of transaction block
ROLLBACK
name | copies
-------+--------
north | 5
south | 2
(2 rows)
The first update would make north negative, so it fails, the transaction is aborted, and neither warehouse changes.
Isolation and locks (in brief)
When many sessions work at the same time, PostgreSQL uses MVCC (multi-version concurrency control): readers see a consistent snapshot and never block writers. Two sessions that update the same row do wait for each other: the second waits until the first commits or rolls back.
| Isolation level | Each statement sees … |
|---|---|
READ COMMITTED (default) |
data committed before that statement started |
REPEATABLE READ |
data committed before the transaction started |
SERIALIZABLE |
as if transactions ran one after another; may fail with a serialization error that you retry |
BEGIN ISOLATION LEVEL REPEATABLE READ;
SHOW transaction_isolation;
SELECT count(*) FROM books;
COMMIT;BEGIN
transaction_isolation
-----------------------
repeatable read
(1 row)
count
-------
20
(1 row)
COMMIT
SELECT … FOR UPDATE locks the selected rows until the transaction ends, which is how you safely "read, then change" a row (for example reserving the last copy of a book).
Test yourself
What does ROLLBACK do?
- Saves the changes
- Undoes all changes since BEGIN
- Undoes only the last statement
- Restarts the server
A statement fails inside BEGIN ... COMMIT. What happens at COMMIT?
- The successful statements are committed
- The whole transaction is rolled back
- Only the failed statement is retried
- PostgreSQL asks what to do
What is a savepoint for?
- Backing up the database
- Rolling back part of a transaction
- Committing early
- Locking a table