SQL Transactions
What you will learn
- What a transaction is and why changes are grouped
- How
BEGIN,COMMITandROLLBACKwork - How a failed step is undone with the rest
- What a savepoint is
This lesson runs on the sample database you chose in lesson 1.1 (use the Example data picker at the top). The changes happen only in your browser's copy of the data; Reset data puts everything back. Run the cells from top to bottom. (Database Fundamentals, chapter 6, explains transactions in depth; this lesson is the practical start.)
1. All or nothing
Some work needs several changes that only make sense together: take money from one account and add it to another; reduce the stock and record the order. If the first change succeeds and the second fails, the data is wrong. A transaction groups the changes so that they happen all together or not at all.
BEGINstarts a transaction.COMMITsaves all the changes made sinceBEGIN.ROLLBACKthrows them all away.
2. A committed transaction
Sell one unit of product 2: lower the stock and add an order line for a new order (shown here simply as a change to two tables).
SELECT stock FROM products WHERE product_id = 2;
stock
-----
150
(1 row)
BEGIN;
UPDATE products SET stock = stock - 1 WHERE product_id = 2;
INSERT INTO orders (customer_id, order_date, status, ship_city) VALUES (1, '2026-10-05', 'paid', 'Leeds');
COMMIT;
(1 row changed)
SELECT (SELECT stock FROM products WHERE product_id = 2) AS stock_now,
(SELECT COUNT(*) FROM orders WHERE order_date = '2026-10-05') AS new_orders;
stock_now new_orders
--------- ----------
149 1
(1 row)
Move 5.00 (500 cents) from account 1 to account 2:
SELECT account_id, balance_cents FROM accounts WHERE account_id IN (1, 2) ORDER BY account_id;
account_id balance_cents
---------- -------------
1 192400
2 52078
(2 rows)
BEGIN;
UPDATE accounts SET balance_cents = balance_cents - 500 WHERE account_id = 1;
UPDATE accounts SET balance_cents = balance_cents + 500 WHERE account_id = 2;
COMMIT;
(1 row changed)
SELECT account_id, balance_cents FROM accounts WHERE account_id IN (1, 2) ORDER BY account_id;
account_id balance_cents
---------- -------------
1 191900
2 52578
(2 rows)
Enrol student 360 in section 1 and lower the section's free capacity by one:
SELECT capacity FROM sections WHERE section_id = 1;
capacity
--------
25
(1 row)
BEGIN;
INSERT INTO enrollments (student_id, section_id, enrolled_on) VALUES (360, 1, '2026-10-05');
UPDATE sections SET capacity = capacity - 1 WHERE section_id = 1;
COMMIT;
(1 row changed)
SELECT (SELECT capacity FROM sections WHERE section_id = 1) AS capacity_now,
(SELECT COUNT(*) FROM enrollments WHERE student_id = 360) AS enrollments_of_360;
capacity_now enrollments_of_360
------------ ------------------
24 5
(1 row)
Both changes are saved together by COMMIT.
3. ROLLBACK: take it back
ROLLBACK ends the transaction and undoes every change since BEGIN. Use it when you realise something is wrong, or when a step fails:
BEGIN;
(done)
UPDATE products SET price = 1 WHERE product_id = 3;
(1 row changed)
SELECT product_id, price FROM products WHERE product_id = 3;
product_id price
---------- -----
3 1.0
(1 row)
ROLLBACK;
SELECT product_id, price FROM products WHERE product_id = 3;
product_id price
---------- -----
3 29.5
(1 row)
BEGIN;
(done)
UPDATE accounts SET balance_cents = 0 WHERE account_id = 3;
(1 row changed)
SELECT account_id, balance_cents FROM accounts WHERE account_id = 3;
account_id balance_cents
---------- -------------
3 0
(1 row)
ROLLBACK;
SELECT account_id, balance_cents FROM accounts WHERE account_id = 3;
account_id balance_cents
---------- -------------
3 62780
(1 row)
BEGIN;
(done)
UPDATE courses SET credits = 1 WHERE course_id = 3;
(1 row changed)
SELECT course_id, credits FROM courses WHERE course_id = 3;
course_id credits
--------- -------
3 1
(1 row)
ROLLBACK;
SELECT course_id, credits FROM courses WHERE course_id = 3;
course_id credits
--------- -------
3 4
(1 row)
Inside the transaction you see your own change; after ROLLBACK the original value is back, as if nothing had happened.
4. A failed step
When a statement inside a transaction breaks a rule, that statement is refused, but the transaction stays open. Your program must end it, normally with ROLLBACK, so the steps that did succeed are undone as well:
Try to take more stock than exists (stock may not go below 0):
BEGIN;
UPDATE orders SET status = 'cancelled' WHERE order_id = 1;
(1 row changed)
UPDATE products SET stock = stock - 1000000 WHERE product_id = 2;
IntegrityError: CHECK constraint failed: stock >= 0
ROLLBACK;
SELECT status FROM orders WHERE order_id = 1;
status
---------
delivered
(1 row)
Try to take more money than the account holds (balance_cents may not go below 0):
BEGIN;
UPDATE accounts SET balance_cents = balance_cents + 500 WHERE account_id = 2;
(1 row changed)
UPDATE accounts SET balance_cents = balance_cents - 1000000000 WHERE account_id = 1;
IntegrityError: CHECK constraint failed: balance_cents >= 0
ROLLBACK;
SELECT account_id, balance_cents FROM accounts WHERE account_id IN (1, 2) ORDER BY account_id;
account_id balance_cents
---------- -------------
1 191900
2 52578
(2 rows)
Try to give a grade above 100 (grades must be between 0 and 100):
BEGIN;
UPDATE sections SET capacity = capacity + 1 WHERE section_id = 2;
(1 row changed)
UPDATE enrollments SET grade = 150 WHERE student_id = 1 AND section_id = 30;
IntegrityError: CHECK constraint failed: grade BETWEEN 0 AND 100
ROLLBACK;
SELECT section_id, capacity FROM sections WHERE section_id = 2;
section_id capacity
---------- --------
2 30
(1 row)
The first step was fine, the second was refused, and ROLLBACK undid the first too: nothing changed. That is the all-or-nothing promise.
5. Savepoints
A savepoint is a named mark inside a transaction. ROLLBACK TO name goes back to the mark without ending the transaction, so earlier work is kept:
CREATE TABLE steps (n INTEGER);
BEGIN;
INSERT INTO steps VALUES (1);
SAVEPOINT after_first;
INSERT INTO steps VALUES (2);
ROLLBACK TO after_first;
INSERT INTO steps VALUES (3);
COMMIT;
SELECT n FROM steps ORDER BY n;
n
-
1
3
(2 rows)
CREATE TABLE steps (n INTEGER);
BEGIN;
INSERT INTO steps VALUES (1);
SAVEPOINT after_first;
INSERT INTO steps VALUES (2);
ROLLBACK TO after_first;
INSERT INTO steps VALUES (3);
COMMIT;
SELECT n FROM steps ORDER BY n;
n
-
1
3
(2 rows)
CREATE TABLE steps (n INTEGER);
BEGIN;
INSERT INTO steps VALUES (1);
SAVEPOINT after_first;
INSERT INTO steps VALUES (2);
ROLLBACK TO after_first;
INSERT INTO steps VALUES (3);
COMMIT;
SELECT n FROM steps ORDER BY n;
n
-
1
3
(2 rows)
Step 2 was undone, step 1 and step 3 were saved.
6. What belongs in a transaction
- The changes that must succeed together: both sides of a transfer, the order and its stock.
- Keep it short. A transaction holds locks and delays others (Database Fundamentals, lesson 6.6).
- No waiting for people or other systems inside it.
- A single
UPDATEorINSERTis already one safe unit; you only needBEGINfor several statements.
In other databases. The idea is the same everywhere; the way you start one differs. SQLite uses
BEGIN(and, by default, treats each statement outside a transaction as its own, saved at once). Check the documentation of your database for its exact syntax and defaults.
Worked example: a transfer
| Step | Statement |
|---|---|
| 1 | BEGIN; |
| 2 | UPDATE accounts SET balance = balance - 100 WHERE id = 1; |
| 3 | UPDATE accounts SET balance = balance + 100 WHERE id = 2; |
| 4 | if both worked: COMMIT; |
| 4b | if either failed: ROLLBACK; |
Without the transaction, a crash between steps 2 and 3 would make 100 disappear. The accounts are made up.
Common mistakes
- Forgetting
COMMIT. The changes are not saved. - Forgetting
ROLLBACKafter an error, leaving the transaction open. - A long transaction that blocks other users.
- Putting unrelated work in one transaction.
- Assuming a failed statement undoes the earlier ones by itself. It does not; you roll back.
Key takeaways
- A transaction makes several changes all-or-nothing:
BEGIN, thenCOMMITorROLLBACK. - A failed statement does not undo the rest; end the transaction with
ROLLBACK. SAVEPOINT/ROLLBACK TOundo part of a transaction.- Keep transactions short and put together only what must succeed together.
Practice
1. Which command saves the changes of a transaction?
Show answer
COMMIT.
2. What does ROLLBACK do?
Show answer
It undoes all the changes made since BEGIN and ends the transaction.
3. Why is a transfer between accounts a transaction?
Show answer
Taking money from one account and adding it to the other must both happen or neither, or money is lost or created.
4. A statement in a transaction fails. What do you do?
Show answer
End the transaction with ROLLBACK, so the steps that succeeded are undone as well.
5. What is a savepoint for?
Show answer
To undo only part of a transaction: ROLLBACK TO name goes back to the mark and keeps the earlier work.
6. Why keep a transaction short?
Show answer
While it is open it can block other users, so it should hold only what must succeed together.