Transactions and isolation levels
- Version
- 19
- Review
- Draft
Summary#
A transaction applies a group of statements together or not at all. At the default READ COMMITTED level, each plain SELECT gets a fresh snapshot. At REPEATABLE READ and SERIALIZABLE, queries use the snapshot established by the first statement that requires one.
Syntax#
BEGIN ISOLATION LEVEL SERIALIZABLE;
statement;
SAVEPOINT name;
statement;
ROLLBACK TO SAVEPOINT name;
COMMIT;
Example#
The output below is from PostgreSQL 19.0, produced with psql -X -q -A -P null=NULL -v ON_ERROR_STOP=1 -f example.sql in a scratch database. The script manages its own transactions and drops its temporary table at the end. It runs in one session, so it shows the commands and not a conflict between sessions.
CREATE TEMPORARY TABLE demo_accounts (
owner text PRIMARY KEY,
balance integer NOT NULL CHECK (balance >= 0)
);
INSERT INTO demo_accounts VALUES ('ava', 100), ('bo', 20);
BEGIN ISOLATION LEVEL SERIALIZABLE;
SHOW transaction_isolation;
UPDATE demo_accounts SET balance = balance - 30 WHERE owner = 'ava';
UPDATE demo_accounts SET balance = balance + 30 WHERE owner = 'bo';
SAVEPOINT before_bonus;
UPDATE demo_accounts SET balance = balance + 500 WHERE owner = 'bo';
ROLLBACK TO SAVEPOINT before_bonus;
COMMIT;
SELECT owner, balance FROM demo_accounts ORDER BY owner;
-- ROLLBACK discards every change made in the transaction.
BEGIN ISOLATION LEVEL REPEATABLE READ;
SHOW transaction_isolation;
DELETE FROM demo_accounts;
SELECT count(*) AS inside FROM demo_accounts;
ROLLBACK;
SELECT count(*) AS afterwards FROM demo_accounts;
DROP TABLE demo_accounts;
Expected output#
transaction_isolation
serializable
(1 row)
owner|balance
ava|70
bo|50
(2 rows)
transaction_isolation
repeatable read
(1 row)
inside
0
(1 row)
afterwards
2
(1 row)
Common mistakes#
ERROR: could not serialize access carries SQLSTATE 40001, which REPEATABLE READ and SERIALIZABLE transactions can raise. Roll back and retry the whole transaction, including the reads and decisions that led to its writes.
ERROR: current transaction is aborted, commands ignored until end of transaction block follows an earlier error in the same transaction. Run ROLLBACK, or roll back to a savepoint, before sending more statements. Set the isolation level before the first query or data modification in the transaction.
Version applicability#
Since PostgreSQL 9.1, SERIALIZABLE detects serialization anomalies, and the earlier snapshot behavior is available as REPEATABLE READ. Requesting READ UNCOMMITTED in PostgreSQL 19 behaves like READ COMMITTED.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0