AI Hints
Home›PostgreSQL Tutorial›Transactions and MVCC
PostgreSQL · Lesson 64 of 120

Transactions

All or nothing.

⏱ 2 min read▶ Video at 57:23🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

A customer buys a book. We must take one from stock, and record the order. If the second step fails, the first must be undone. A transaction makes several steps all or nothing.

  • Take from stock
  • Record the order
  • All or nothing

Commit and rollback

Begin starts a transaction. We take one book from stock, then change our mind, and roll back. The stock is unchanged. Then the same with commit, which saves it. Run it. Fifty eight, then fifty seven.

query.sqlsql
BEGIN;
UPDATE books SET stock = stock - 1 WHERE book_id = 1;
ROLLBACK;
SELECT stock FROM books WHERE book_id = 1;

BEGIN;
UPDATE books SET stock = stock - 1 WHERE book_id = 1;
COMMIT;
SELECT stock FROM books WHERE book_id = 1;
Output
BEGIN
UPDATE 1
ROLLBACK
 stock
-------
    58
(1 row)

BEGIN
UPDATE 1
COMMIT
 stock
-------
    57
(1 row)

An error aborts it

Inside a transaction, after an error, Postgres refuses everything until you roll back. That keeps half finished work out. Run it. The second update is refused, and nothing is saved.

query.sqlsql
BEGIN;
UPDATE books SET stock = stock - 1 WHERE book_id = 1;
UPDATE books SET stock = -5 WHERE book_id = 2;   -- breaks a CHECK rule
UPDATE books SET stock = stock - 1 WHERE book_id = 3;
COMMIT;
SELECT book_id, stock FROM books WHERE book_id IN (1, 2, 3) ORDER BY 1;
Output
BEGIN
UPDATE 1
ERROR:  new row for relation "books" violates check constraint "books_stock_check"
DETAIL:  Failing row contains (2, Code of the River, Tom Avery, Thriller, 12.99, -5,
2021, {twist,fast-paced}, {"pages": 353, "format": "hardcover", "language": "English"},
A river pilot finds a coded message in a drowned boat and is pul...).
ERROR:  current transaction is aborted, commands ignored until end of transaction block
ROLLBACK
 book_id | stock
---------+-------
       1 |    58
       2 |    26
       3 |    47
(3 rows)

Summary

Begin, commit and rollback make several steps all or nothing, and an error aborts the whole transaction. Next, savepoints.

Key takeaways
  • BEGIN
  • COMMIT
  • ROLLBACK
Next up: Savepoints — undo just part