19. Transactions: all or nothing

Some changes belong together: either all of them happen, or none does. A transaction is how you tell the database which ones.

Why changes need to go together

Think of what happens when a customer orders. The shop must:

  1. add the order to orders,
  2. add each thing ordered to order_item,
  3. take what was sold off each product's stock.

That is several statements. Suppose the power goes out after step 2: there is an order, but the stock still counts goods that have been sold. Or step 2 fails halfway: an order with half its lines. Either way the data no longer tells the truth, and nobody may notice for weeks.

Moving money is the textbook case: taking 500 baht from one account and adding it to another must both happen, or neither; money must never vanish in between, nor appear twice.

A transaction puts statements together into one unit: the database makes all of them happen, or none of them. Never half.

BEGIN and COMMIT

BEGIN starts a transaction. The statements after it are kept apart, not yet final. COMMIT makes them all final at once. Customer 9 orders 2 Coffees and 3 Potato Chips:

SELECT id, name, stock FROM product WHERE id IN (1, 7);
idnamestock
1Coffee120
7Potato Chips200
2 rows
BEGIN;
INSERT INTO orders (id, customer_id, ordered, status) VALUES (16, 9, '2026-12-01', 'paid');
INSERT INTO order_item (order_id, product_id, qty, price) VALUES (16, 1, 2, 55), (16, 7, 3, 25);
UPDATE product SET stock = stock - 2 WHERE id = 1;
UPDATE product SET stock = stock - 3 WHERE id = 7;
COMMIT;
✓ Done
SELECT id, name, stock FROM product WHERE id IN (1, 7);
SELECT * FROM order_item WHERE order_id = 16;
idnamestock
1Coffee118
7Potato Chips197
2 rows
order_idproduct_idqtyprice
161255.0
167325.0
2 rows

The Coffee went from 120 to 118 and the Potato Chips from 200 to 197, and the order and its two lines are there: everything together.

What about every statement in the chapters before, with no BEGIN? The database runs each one in a transaction of its own, made final as soon as it ends. This is called autocommit. That is why, in chapter 16, an INSERT of several rows with one bad row added none of them: the statement was one small transaction.

ROLLBACK: taking it all back

ROLLBACK ends a transaction the other way: everything since BEGIN is undone, as if it had never happened. Here are the stationery prices before:

SELECT id, name, price FROM product WHERE category_id = 4;
idnameprice
10Notebook30.0
11Pen15.0
12Highlighter25.0
3 rows

Someone doubles them, by mistake, inside a transaction. Inside it, the change is there to see:

BEGIN;
UPDATE product SET price = price * 2 WHERE category_id = 4;
SELECT id, name, price FROM product WHERE category_id = 4;
idnameprice
10Notebook60.0
11Pen30.0
12Highlighter50.0
3 rows

The mistake is spotted before COMMIT. ROLLBACK, and the prices are as they were:

ROLLBACK;
SELECT id, name, price FROM product WHERE category_id = 4;
idnameprice
10Notebook30.0
11Pen15.0
12Highlighter25.0
3 rows

This is the safety net chapter 17 promised: for a big UPDATE or DELETE, BEGIN first, change, look with a SELECT, then COMMIT if it is right or ROLLBACK if it isn't.

When a statement fails inside a transaction, the database undoes that statement, but the transaction stays open: what to do next is up to you (or your program). Here an order is begun, and then one of its lines points at a product that doesn't exist:

BEGIN;
INSERT INTO orders (id, customer_id, ordered, status) VALUES (17, 10, '2026-12-01', 'paid');
✓ 1 row changed
INSERT INTO order_item (order_id, product_id, qty, price) VALUES (17, 99, 1, 10);
Error: FOREIGN KEY constraint failed

An order without its lines must not stay, so take the whole thing back:

ROLLBACK;
SELECT count(*) FROM orders WHERE id = 17;
count(*)
0
1 row

0: order 17 is gone with the rest.

A program must end every transaction it begins, with COMMIT or ROLLBACK. A transaction left open keeps its changes out of everyone else's sight, and (below) can keep everyone else from writing. If the program ends or the connection closes before COMMIT, the database takes the changes back.

SAVEPOINT: taking back part of it

Sometimes you want to undo only the last few steps, not the whole transaction. SAVEPOINT name marks a point; ROLLBACK TO name goes back to it and keeps what came before; RELEASE name drops the mark and keeps everything.

BEGIN;
UPDATE product SET price = price + 5 WHERE category_id = 1;
SAVEPOINT before_snacks;
UPDATE product SET price = price + 5 WHERE category_id = 3;
SELECT id, name, price FROM product WHERE category_id IN (1, 3);
idnameprice
1Coffee60.0
2Green Tea50.0
3Orange Juice45.0
7Potato Chips30.0
8Dried Mango95.0
9Cashew Nuts155.0
6 rows

The drinks and the snacks are both 5 baht up. The snacks, it turns out, should stay as they were:

ROLLBACK TO before_snacks;
RELEASE before_snacks;
COMMIT;
SELECT id, name, price FROM product WHERE category_id IN (1, 3);
idnameprice
1Coffee60.0
2Green Tea50.0
3Orange Juice45.0
7Potato Chips25.0
8Dried Mango90.0
9Cashew Nuts150.0
6 rows

The drinks keep their new prices; the snacks are back where they were. ROLLBACK TO doesn't end the transaction: after it you can go on and change more, then COMMIT or ROLLBACK as usual. Savepoints can sit inside one another, each with its own name.

ACID in plain words

The promises a transaction makes are often called ACID, after their four English initials:

LetterWordWhat it means for the shop
AAtomicityAll of a transaction happens, or none of it. No order without its lines.
CConsistencyEvery rule of the tables (NOT NULL, UNIQUE, foreign keys...) still holds after each transaction.
IIsolationOthers don't see a transaction's changes until its COMMIT; they see the data as it was before.
DDurabilityAfter COMMIT says done, the change is on the disk: a power cut a second later doesn't lose it.

Phai SQL keeps all four, the same way SQLite does, and its files are SQLite files, so a transaction left halfway by a power cut is undone the next time the file is opened, by either program.

One writer at a time

Many people can read a database at once, but only one transaction writes at a time. When a second one wants to write while the first is still at it, it waits for the first to finish (the database holds a lock, a sign on the door saying "busy"). If it waits too long, it gets the error database is locked. This is the main reason to keep transactions short: BEGIN, change, COMMIT, without waiting in between for a person to click something.

A database file can keep its changes in one of two ways, its journal mode:

Phai SQL does both, as SQLite does. Either way, still one writer at a time.

  1. In a transaction, delete order 2 and its lines (lines first), look that it is gone, then ROLLBACK and look that it is back.
  2. Begin a transaction, add 10 to the stock of every product, set a savepoint, set the stock of every product to 0, go back to the savepoint, and commit. How many Pens (id 11) are there at the end?
Show the answer
BEGIN;
DELETE FROM order_item WHERE order_id = 2;
DELETE FROM orders WHERE id = 2;
SELECT count(*) FROM orders WHERE id = 2;
ROLLBACK;
SELECT count(*) FROM orders WHERE id = 2;
BEGIN;
UPDATE product SET stock = stock + 10;
SAVEPOINT s1;
UPDATE product SET stock = 0;
ROLLBACK TO s1;
COMMIT;
SELECT id, name, stock FROM product WHERE id = 11;
count(*)
0
1 row
count(*)
1
1 row
idnamestock
11Pen310
1 row

Phai (bamboo), given as a gift of knowledge: free to use, learn from and pass on · every example on this page was run on Phai SQL and checked against SQLite when the page was made