Sub topic 1
What a Transaction Is and Why It Exists
Prerequisites
You should know basic SQL (SELECT, INSERT, UPDATE, DELETE) and how tables, primary keys and constraints work. You should also understand that several users or programs can use a database at the same time. The examples use PostgreSQL syntax.
What a transaction is and why it exists
A transaction is a group of SQL statements that the database treats as one unit of work. Either every statement in the group takes effect, or none does. Transactions exist because one business action often changes several rows. A bank transfer subtracts money from one account and adds it to another. If the system stops between those two steps, money is lost or created.
Controlling a transaction with BEGIN, COMMIT and ROLLBACK
BEGINstarts a transaction.COMMITmakes the changes in the transaction permanent.ROLLBACKdiscards every change made sinceBEGIN.
Create a small table and run a transfer:
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;Until COMMIT runs, other sessions see the old balances. If you run ROLLBACK instead, both updates disappear.
Atomicity: all or nothing
Atomicity means a transaction completes fully or not at all. The database keeps track of what each transaction changed. If the transaction fails or is rolled back, the database undoes those changes. Application code should check for errors and always end a transaction with COMMIT or ROLLBACK.
Consistency: constraints and valid states
Consistency means a transaction moves the database from one valid state to another. Rules such as CHECK, NOT NULL, primary keys and foreign keys define what a valid state is. If a statement breaks one of these rules, the database rejects it.
BEGIN;
UPDATE accounts SET balance = balance - 500 WHERE id = 1;
-- Fails: the balance would become negative, so the CHECK constraint rejects it.
ROLLBACK;
SELECT balance FROM accounts WHERE id = 1;
-- Returns 70.00, the value from before the failed transaction.Exercise
Account 1 has a balance of 70.00. Inside one transaction you subtract 20 from account 1, then run ROLLBACK. What is the balance of account 1afterwards?
Show answer
70.00. ROLLBACK discards the subtraction, so the balance returns to its value before BEGIN.