Sub topic 12
Grouping Changes in a Transaction
Why transactions matter
Assume you know basic SELECT, INSERT, UPDATE, and DELETE, and that PostgreSQL 12 or newer is running with the books and readings tables already created.
A transaction is a group of database operations that PostgreSQL treats as one unit. The database saves all of the operations together, or saves none of them. This property is called atomicity.
For example, adding a book and creating its reading entry are related changes. If the book insert succeeds but the reading insert fails, the database should not keep only half of the operation.
BEGIN, COMMIT, and ROLLBACK
Use BEGIN to start a transaction. Use COMMIT to make its changes permanent. Use ROLLBACK to discard all changes made since BEGIN.
This example creates a book and a matching reading entry in one transaction. The data-modifying common table expression, or CTE, passes the new book's generated ID to the second insert.
BEGIN;
WITH new_book AS (
INSERT INTO books (title, isbn13, published_year, page_count)
VALUES ('Another Example', '9780000000002', 2024, 280)
RETURNING book_id
)
INSERT INTO readings (book_id, status)
SELECT book_id, 'want_to_read'
FROM new_book;
COMMIT;The RETURNING clause returns the generated primary key from the first insert. The second insert uses that key without guessing it or querying by title.
If an operation fails, issue ROLLBACK instead of COMMIT:
BEGIN;
INSERT INTO books (title, isbn13)
VALUES ('Temporary Book', '9780000000003');
-- This violates the rating constraint because the rating is too high.
INSERT INTO readings (book_id, status, rating)
SELECT book_id, 'want_to_read', 8
FROM books
WHERE isbn13 = '9780000000003';
ROLLBACK;After the rollback, Temporary Book is not present. PostgreSQL also rolls back the successful first insert because both inserts belonged to the same transaction.
When to use a transaction
Use a transaction when several changes must remain consistent:
- Creating a parent row and its related child rows.
- Updating an account balance and recording the transfer.
- Removing a book and dependent records together.
- Importing a batch where a partial import would be invalid.
A transaction does not make every operation faster. It defines the boundary for all-or-nothing behavior. Keep transactions short so they hold locks for less time and reduce contention with other sessions.
PostgreSQL normally makes changes visible to other sessions only after COMMIT. If a process stops before the commit, PostgreSQL rolls back the unfinished transaction during recovery.
Common errors
Do not call COMMIT after only the first step of a multi-step change. That defeats atomicity. Also avoid leaving a transaction open while waiting for user input or network requests. A long-running transaction can keep old row versions and locks alive.
For operations that may be safely repeated, combine a transaction with an idempotent statement such as INSERT ... ON CONFLICT. The transaction protects the group, while the conflict rule controls repeated input.
Exercise
If the book insert succeeds but the reading insert violates a CHECK constraint, what should you run to prevent the book from being saved?
Show answer
Run ROLLBACK. It discards every change made since BEGIN, including the successful book insert.