Sub topic 12
Grouping changes in a transaction
This chapter assumes you have the books, authors, book_authors, and readings tables from the earlier chapters, and that you can run several statements in one psql session. Earlier chapters used data-modifying CTEs and ON CONFLICT. Here you learn what to do when a change needs more than one statement.
Why one statement is not always enough
Adding a book to your log takes two writes: a row in books and a row in readings that points to it. If the first write succeeds and the second fails, you have a book with no reading entry. Nothing in the schema forbids that state, so your application would have to find and repair it.
A transaction groups statements into one unit of work with all-or-nothing behavior. Either every change becomes visible to other sessions, or none does. This property is called atomicity. It is the "A" in ACID, along with consistency, isolation, and durability.
Autocommit and explicit transactions
Outside a transaction block, PostgreSQL treats each statement as its own transaction and commits it as soon as it finishes. This is autocommit. A single INSERT is therefore already atomic by itself: it adds all its rows or none.
To group several statements, wrap them in BEGIN and COMMIT:
BEGIN;
INSERT INTO books (title, isbn13)
VALUES ('Another Example', '9780000000002');
INSERT INTO readings (book_id)
SELECT book_id FROM books WHERE isbn13 = '9780000000002';
COMMIT;Until COMMIT, other sessions cannot see either row. Your own session sees both, so the second statement can find the book the first one created. After COMMIT, both rows become visible at the same moment and survive a crash.
| Command | Effect |
|---|---|
| `BEGIN` (or `START TRANSACTION`) | Opens a transaction block. |
| `COMMIT` | Makes all changes permanent and visible to others. |
| `ROLLBACK` | Discards all changes made since `BEGIN`. |
| `SAVEPOINT name` | Marks a point inside the transaction you can return to. |
| `ROLLBACK TO SAVEPOINT name` | Undoes work after the savepoint and keeps the transaction open. |
What happens when a statement fails
In PostgreSQL, an error inside a transaction block puts the whole transaction into an aborted state. Every later statement is rejected until you end the block. Suppose the second insert violates a constraint. The readings table allows a rating only on finished books:
BEGIN;
INSERT INTO books (title, isbn13)
VALUES ('Failing Example', '9780000000005');
INSERT INTO readings (book_id, status, rating)
SELECT book_id, 'reading', 5 FROM books WHERE isbn13 = '9780000000005';
-- ERROR: new row for relation "readings" violates check constraint
SELECT count(*) FROM books;
-- ERROR: current transaction is aborted, commands ignored until end of transaction block
ROLLBACK;The ROLLBACK discards the new book as well. Even if you type COMMIT in an aborted transaction, PostgreSQL performs a rollback and reports ROLLBACK. It never commits the half-finished work.
In psql you can see the state in the prompt if you set \set PROMPT1 '%/%x%R%# '. The %x shows * inside a transaction and ! in an aborted one.
Scripts and ON_ERROR_STOP
When you run a SQL file through psql, a failed statement does not stop the script by default. Later statements still run. Inside a transaction block they all fail with the "aborted" error, but outside one, they run normally. For loading scripts, set the following:
\set ON_ERROR_STOP on
BEGIN;
-- your inserts here
COMMIT;With ON_ERROR_STOP, psql exits on the first error. The connection closes, and PostgreSQL rolls back the open transaction. You can also run psql --single-transaction -f load.sql, which wraps the entire file in BEGIN and COMMIT.
Savepoints: partial recovery
Sometimes you want to keep earlier work when one step fails. A savepoint lets you roll back part of a transaction:
BEGIN;
INSERT INTO books (title, isbn13)
VALUES ('Batch One', '9780000000003');
SAVEPOINT before_second;
INSERT INTO books (title, isbn13)
VALUES ('Batch Two', '123');
-- ERROR: violates check constraint (isbn13 must be 13 digits)
ROLLBACK TO SAVEPOINT before_second;
INSERT INTO books (title, isbn13)
VALUES ('Batch Two', '9780000000004');
COMMIT;After ROLLBACK TO SAVEPOINT, the transaction is usable again. "Batch One" and the corrected "Batch Two" are both committed. Savepoints cost a little overhead each, so use them where a partial failure is expected, such as importing many rows where some may be bad. Do not add one before every statement.
Data-modifying CTEs are already atomic
The CTE from the loading chapter inserts a book, an author, and the link row in one statement:
WITH new_book AS (
INSERT INTO books (title, isbn13, published_year, page_count)
VALUES ('Example Title', '9780000000001', 2001, 320)
RETURNING book_id
), new_author AS (
INSERT INTO authors (name)
VALUES ('Example Author')
RETURNING author_id
)
INSERT INTO book_authors (book_id, author_id)
SELECT book_id, author_id FROM new_book, new_author;A single statement is atomic by itself, so you do not need BEGIN here. Use an explicit transaction when the steps are separate statements. This happens when your application needs to read a result and decide what to do next, or when you mix inserts, updates, and deletes across tables.
Things a rollback does not undo
Rollback restores table contents, but it has limits you should know about.
- Identity counters. A value taken from the sequence behind
GENERATED ALWAYS AS IDENTITYis not given back on rollback. After a failed insert, the nextbook_idskips a number. This is intentional, because it lets concurrent sessions get ids without waiting on each other. Never rely on ids being gap-free. - Side effects outside the database. If your application sends an email or calls an API between
BEGINandCOMMIT, a rollback cannot recall it. Do those things after the commit. - Time inside a transaction.
now()andcurrent_timestampreturn the time the transaction started, not the time of each statement. Two inserts in one transaction get the samenow(). Useclock_timestamp()if you need the real clock.
PostgreSQL also supports transactional DDL. You can put CREATE TABLE, ALTER TABLE, and CREATE INDEX inside a transaction and roll them back. This makes schema migrations safer, because a failed step can leave the schema unchanged. A few commands, such as CREATE INDEX CONCURRENTLY, cannot run inside a transaction block.
Concurrency in brief
The default isolation level is READ COMMITTED. Each statement sees the data committed before that statement began. Two consequences matter for this database:
- A query run twice in the same transaction can return different results if another session commits in between.
- A check-then-insert pattern is unsafe. If you run
SELECTto see whether an ISBN exists and thenINSERTwhen it does not, another session can insert the same ISBN between your two statements. Your insert then fails on theUNIQUEconstraint. Let the constraint decide, and useINSERT ... ON CONFLICTas the previous chapter showed.
If you need one snapshot for several queries, such as a report that must add up, use BEGIN ISOLATION LEVEL REPEATABLE READ;. Under this level, transactions that conflict on the same rows can fail with a serialization error, and your application must be ready to retry. The default is fine for the book log.
Practical rules
- Keep transactions short. An open transaction holds locks on rows it has changed, and it can delay cleanup of old row versions by
VACUUM. - Never leave a session idle inside a transaction while waiting for user input.
- Put related writes in one transaction, and put unrelated ones in separate transactions so one failure does not discard the other.
- Handle errors by issuing
ROLLBACK(orROLLBACK TO SAVEPOINT) before sending any more statements.
Exercise
You run BEGIN, insert a book, then insert a reading with status 'wanttoread' and rating 4, which violates the CHECK constraint. You then run COMMIT. Is the book in the table afterward, and why? What would you change to keep the book while skipping the bad reading?
Show answer
The book is not in the table. The failed statement put the transaction into the aborted state, and COMMIT in that state performs a rollback, discarding both inserts. To keep the book, create a savepoint after the book insert, run the reading insert, and on error use ROLLBACK TO SAVEPOINT before continuing and committing. Alternatively, commit the book insert in its own transaction first.
Exercise
A transaction inserts a book, which gets book_id 7, and then rolls back. The next successful insert into books gets which id, and why?
Show answer
It gets 8 or higher, not 7. Identity values come from a sequence, and sequence increments are not undone by rollback. This lets concurrent sessions obtain ids without blocking one another, so gaps in ids are normal.