Sub topic 2
Controlling a Transaction with BEGIN, COMMIT and ROLLBACK
This chapter assumes you know basic SQL statements such as SELECT and UPDATE, and that you understand tables, primary keys, and constraints. The examples use PostgreSQL syntax.
A transaction is a group of database statements treated as one unit of work. A transaction starts with BEGIN. It ends when you permanently save the changes with COMMIT or discard them with ROLLBACK.
This matters when several changes belong together. For example, a money transfer must subtract money from one account and add it to another. Saving only one of those changes would corrupt the account balances.
The transaction commands
BEGINstarts an explicit transaction.COMMITmakes all changes in the transaction permanent.ROLLBACKremoves all changes made since the transaction began.
CREATE TABLE accounts (
id integer PRIMARY KEY,
balance numeric(12, 2) NOT NULL CHECK (balance >= 0)
);
INSERT INTO accounts (id, balance)
VALUES (1, 100.00), (2, 50.00);
BEGIN;
UPDATE accounts
SET balance = balance - 30
WHERE id = 1;
UPDATE accounts
SET balance = balance + 30
WHERE id = 2;
COMMIT;
SELECT * FROM accounts ORDER BY id;After the COMMIT, account 1 has 70.00 and account 2 has 80.00. Other database sessions can then observe both updates as the committed result.
If something goes wrong, roll back instead:
BEGIN;
UPDATE accounts
SET balance = balance - 500
WHERE id = 1;
-- The CHECK constraint rejects a negative balance.
ROLLBACK;
SELECT balance
FROM accounts
WHERE id = 1;The failed operation does not leave the attempted withdrawal in the table. The balance remains the value from before this transaction.
What other sessions can see
Until COMMIT, your changes are normally private to your transaction. Other sessions see the previously committed data. After ROLLBACK, they see no effect from your discarded work.
Common mistakes
Do not commit after only the first half of a multi-step operation. If the second statement fails, the database cannot automatically undo the already committed first statement.
Do not assume that a transaction lasts forever. A long transaction can hold locks, keep old row versions in use, and delay cleanup. Keep the transaction focused, and commit or roll back promptly.
If a statement fails inside a PostgreSQL transaction, the transaction enters an aborted state. You must issue ROLLBACK before starting useful work again.
Exercise
You transfer 25 units from account 1 to account 2. The debit succeeds, but the credit fails. Which command should the application issue before retrying the complete transfer?
Show answer
ROLLBACK. It discards the successful debit so the complete transfer can be retried from the original balances.