TExcelTAD
Home › SQL › SQL Transactions

SQL Transactions

A transaction groups several statements into one unit of work: either all of them take effect, or none do. The classic example is a bank transfer — taking money from one account and adding it to another must never stop half-way.

sql
BEGIN;            -- or BEGIN TRANSACTION / START TRANSACTION
  statement 1;
  statement 2;
COMMIT;           -- make all changes permanent
-- or
ROLLBACK;         -- undo everything since BEGIN

ACID

Transactions give four guarantees, known as ACID:

Property Meaning
Atomicity all or nothing
Consistency constraints hold before and after
Isolation concurrent transactions don't see each other's half-done work
Durability once committed, changes survive a crash

COMMIT

Moving 10 units of stock from one product to another (say, relabelled packs) and logging it:

sql · try it yourself
CREATE TABLE stock_log (product_id INTEGER, change INTEGER, note TEXT);

BEGIN;
UPDATE products SET stock = stock - 10 WHERE product_id = 2;
UPDATE products SET stock = stock + 10 WHERE product_id = 5;
INSERT INTO stock_log VALUES (2, -10, 'relabel'), (5, 10, 'relabel');
COMMIT;

SELECT product_id, name, stock FROM products WHERE product_id IN (2, 5) ORDER BY product_id;
SELECT * FROM stock_log;
1 row affected.

1 row affected.

2 rows affected.

product_id | name           | stock
-----------+----------------+------
2          | Green Tea      | 110
5          | Chai Latte Mix | 42
(2 rows)

product_id | change | note
-----------+--------+--------
2          | -10    | relabel
5          | 10     | relabel
(2 rows)

ROLLBACK

Changed your mind? ROLLBACK throws away every change since BEGIN:

sql · try it yourself
BEGIN;
DELETE FROM orders WHERE status = 'cancelled';
SELECT COUNT(*) AS orders_inside_tx FROM orders;
ROLLBACK;

SELECT COUNT(*) AS orders_after_rollback FROM orders;
7 rows affected.

orders_inside_tx
----------------
33
(1 row)

orders_after_rollback
---------------------
40
(1 row)

Inside the transaction the 7 cancelled orders were gone; after the rollback they are back.

Rolling back on errors

In application code the usual pattern is: begin, run the statements, commit — and if any statement fails, roll back. Here the second update violates NOT NULL, so the transfer must not happen at all:

sql
BEGIN;
UPDATE products SET stock = stock - 5 WHERE product_id = 1;
UPDATE products SET price = NULL WHERE product_id = 1;   -- fails!
COMMIT;
-- application catches the error and runs ROLLBACK instead of COMMIT
sql · try it yourself
CREATE TABLE accounts (id INTEGER PRIMARY KEY, owner TEXT, balance REAL NOT NULL CHECK (balance >= 0));
INSERT INTO accounts VALUES (1, 'Corner Cafe', 100), (2, 'Bright Bytes', 20);

BEGIN;
UPDATE accounts SET balance = balance + 150 WHERE id = 2;
SELECT id, owner, balance FROM accounts ORDER BY id;
-- the matching withdrawal would make account 1 negative:
UPDATE accounts SET balance = balance - 150 WHERE id = 1;
COMMIT;
2 rows affected.

1 row affected.

id | owner        | balance
---+--------------+--------
1  | Corner Cafe  | 100
2  | Bright Bytes | 170
(2 rows)

Error: CHECK constraint failed: balance >= 0

The playground stops at the error, so COMMIT is never reached. Your application would now issue ROLLBACK, and account 2 would be back at 20 — the half-finished transfer never becomes visible to anyone else.

Note: By default each statement outside BEGIN … COMMIT is its own transaction (autocommit). A single UPDATE touching 1,000 rows is already all-or-nothing.

Savepoints

A savepoint marks a point inside a transaction you can roll back to, without abandoning the whole transaction:

sql · try it yourself
BEGIN;
UPDATE products SET price = price + 1 WHERE category_id = 8;
SAVEPOINT before_discount;
UPDATE products SET price = price * 0.5 WHERE category_id = 8;
ROLLBACK TO before_discount;      -- undo only the discount
COMMIT;

SELECT name, price FROM products WHERE category_id = 8 ORDER BY product_id;
3 rows affected.

3 rows affected.

name                   | price
-----------------------+------
Learn Rust in Practice | 40
Python Recipes         | 35.5
The SQL Handbook       | 30
(3 rows)

The +1 survived; the 50 % discount was undone.

Syntax by database

Database Start Savepoint
SQLite BEGIN (DEFERRED / IMMEDIATE / EXCLUSIVE) SAVEPOINT s, ROLLBACK TO s, RELEASE s
PostgreSQL BEGIN / START TRANSACTION same
MySQL (InnoDB) START TRANSACTION / BEGIN same
SQL Server BEGIN TRANSACTION SAVE TRANSACTION s, ROLLBACK TRANSACTION s

Tip: Keep transactions short. While a transaction holds locks, other writers may have to wait (in SQLite, the whole database is locked for writing).

Test yourself

What does ROLLBACK do?

  1. Saves the changes
  2. Undoes all changes since BEGIN
  3. Undoes only the last statement
  4. Deletes the table

Which ACID property means 'all or nothing'?

  1. Atomicity
  2. Consistency
  3. Isolation
  4. Durability

What does ROLLBACK TO sp do?

  1. Ends the transaction
  2. Undoes changes made after savepoint sp, keeping the transaction open
  3. Commits up to sp
  4. Deletes the savepoint only