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.
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)
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 ruleUPDATE 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)