Database Transactions and ACID · Lesson 41 of 112

Database What a Transaction Is

What you will learn

  • Why a change made of several steps can leave data broken if it stops halfway
  • What a transaction is
  • The idea of all or nothing
  • How to start a transaction and undo it

This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top), and it changes data in your browser's copy. The examples build on each other from top to bottom, so run them in order; Reset data starts again. The SQL box sends each statement to the database as you run it, and each one is saved at once unless you open a transaction yourself with BEGIN: that is what this lesson is about.

1. The problem: a change with several steps

Moving 200.00 from one account to another is one idea for a person, but two steps for a database: subtract from the first account, then add to the second. (Money is stored in cents, so 200.00 is 20000.) These are accounts 5 and 6:

SELECT account_id, balance_cents FROM accounts WHERE account_id IN (5, 6) ORDER BY account_id;
SELECT SUM(balance_cents) AS total_cents FROM accounts WHERE account_id IN (5, 6);
account_id  balance_cents
----------  -------------
         5         153100
         6         218400
(2 rows)

total_cents
-----------
     371500
(1 row)

Now suppose the program is stopped (power cut, crash, error) after the first step but before the second:

UPDATE accounts SET balance_cents = balance_cents - 20000 WHERE account_id = 5;
(1 row changed)

(crash here!) Look at the data:

SELECT account_id, balance_cents FROM accounts WHERE account_id IN (5, 6) ORDER BY account_id;
SELECT SUM(balance_cents) AS total_cents FROM accounts WHERE account_id IN (5, 6);
account_id  balance_cents
----------  -------------
         5         133100
         6         218400
(2 rows)

total_cents
-----------
     351500
(1 row)

The two accounts together have 20000 cents less than before: 200.00 has vanished. No single step was wrong; the gap between the steps was. Repair the example before going on:

UPDATE accounts SET balance_cents = balance_cents + 20000 WHERE account_id = 5;
(1 row changed)

Placing an order is one idea for a customer, but several steps for a database: add the order row, add its line, and reduce the stock. First look at the starting state: no order is without lines, and product 2 has some stock:

SELECT COUNT(*) AS orders_without_lines
FROM orders o
LEFT JOIN order_items i ON i.order_id = o.order_id
WHERE i.order_id IS NULL;
SELECT product_id, name, stock FROM products WHERE product_id = 2;
orders_without_lines
--------------------
                   0
(1 row)

product_id  name         stock
----------  -----------  -----
         2  Ceramic mug    150
(1 row)

Now suppose the program is stopped (power cut, crash, error) after the first step but before the others:

INSERT INTO orders (order_id, customer_id, order_date, status, ship_city)
VALUES (2601, 1, '2026-10-01', 'pending', 'Leeds');
(1 row changed)

(crash here!) Look at the data:

SELECT COUNT(*) AS orders_without_lines
FROM orders o
LEFT JOIN order_items i ON i.order_id = o.order_id
WHERE i.order_id IS NULL;
SELECT product_id, name, stock FROM products WHERE product_id = 2;
orders_without_lines
--------------------
                   1
(1 row)

product_id  name         stock
----------  -----------  -----
         2  Ceramic mug    150
(1 row)

There is now an order with no lines, and the stock was never reduced. No single step was wrong; the gap between the steps was. Repair the example before going on:

DELETE FROM orders WHERE order_id = 2601;
(1 row changed)

Moving a student from one section to another is one idea for the office, but two steps for a database: add the enrollment in the new section, then remove the old one. Student 1 is in sections 19, 30 and 41. We move the student from section 30 to section 31, the same course in the next term:

SELECT student_id, section_id, grade FROM enrollments WHERE student_id = 1 ORDER BY section_id;
student_id  section_id  grade
----------  ----------  -----
         1          19   NULL
         1          30   49.2
         1          41   60.8
(3 rows)

Now suppose the program is stopped (power cut, crash, error) after the first step but before the second:

INSERT INTO enrollments (student_id, section_id, enrolled_on) VALUES (1, 31, '2026-01-20');
(1 row changed)

(crash here!) Look at the data:

SELECT student_id, section_id, grade FROM enrollments WHERE student_id = 1 ORDER BY section_id;
student_id  section_id  grade
----------  ----------  -----
         1          19   NULL
         1          30   49.2
         1          31   NULL
         1          41   60.8
(4 rows)

The student is now enrolled in both terms of the same course. No single step was wrong; the gap between the steps was. Repair the example before going on:

DELETE FROM enrollments WHERE student_id = 1 AND section_id = 31;
(1 row changed)

2. The idea: a transaction

A transaction is a group of steps that the database treats as one unit of work:

  • either all the steps take effect (the transaction is committed), or
  • none of them do (it is rolled back).

This is all or nothing. Nobody ever sees, or keeps, the half-finished state. BEGIN opens the transaction. Inside it the program sees its own changes. ROLLBACK throws all of them away, and the data is exactly as it was before BEGIN:

BEGIN;
UPDATE accounts SET balance_cents = balance_cents - 20000 WHERE account_id = 5;
SELECT account_id, balance_cents FROM accounts WHERE account_id IN (5, 6) ORDER BY account_id;
ROLLBACK;
SELECT account_id, balance_cents FROM accounts WHERE account_id IN (5, 6) ORDER BY account_id;
account_id  balance_cents
----------  -------------
         5         133100
         6         218400
(2 rows)

account_id  balance_cents
----------  -------------
         5         153100
         6         218400
(2 rows)

The first table is what the program sees inside the transaction; the second is the data after the rollback.

BEGIN;
INSERT INTO orders (order_id, customer_id, order_date, status, ship_city)
VALUES (2601, 1, '2026-10-01', 'pending', 'Leeds');
INSERT INTO order_items (order_id, line_no, product_id, quantity, unit_price) VALUES (2601, 1, 2, 2, 44.1);
UPDATE products SET stock = stock - 2 WHERE product_id = 2;
SELECT COUNT(*) AS lines FROM order_items WHERE order_id = 2601;
SELECT stock FROM products WHERE product_id = 2;
ROLLBACK;
SELECT COUNT(*) AS lines FROM order_items WHERE order_id = 2601;
SELECT stock FROM products WHERE product_id = 2;
lines
-----
    1
(1 row)

stock
-----
  148
(1 row)

lines
-----
    0
(1 row)

stock
-----
  150
(1 row)

The first two tables are what the program sees inside the transaction; the last two are the data after the rollback: no line, and the stock is back.

BEGIN;
INSERT INTO enrollments (student_id, section_id, enrolled_on) VALUES (1, 31, '2026-01-20');
DELETE FROM enrollments WHERE student_id = 1 AND section_id = 30;
SELECT student_id, section_id, grade FROM enrollments WHERE student_id = 1 ORDER BY section_id;
ROLLBACK;
SELECT student_id, section_id, grade FROM enrollments WHERE student_id = 1 ORDER BY section_id;
student_id  section_id  grade
----------  ----------  -----
         1          19   NULL
         1          31   NULL
         1          41   60.8
(3 rows)

student_id  section_id  grade
----------  ----------  -----
         1          19   NULL
         1          30   49.2
         1          41   60.8
(3 rows)

The first table is what the program sees inside the transaction; the second is the data after the rollback: section 30 and its grade are back.

The happy path ends with COMMIT instead:

BEGIN;
UPDATE accounts SET balance_cents = balance_cents - 20000 WHERE account_id = 5;
UPDATE accounts SET balance_cents = balance_cents + 20000 WHERE account_id = 6;
COMMIT;
SELECT account_id, balance_cents FROM accounts WHERE account_id IN (5, 6) ORDER BY account_id;
SELECT SUM(balance_cents) AS total_cents FROM accounts WHERE account_id IN (5, 6);
account_id  balance_cents
----------  -------------
         5         133100
         6         238400
(2 rows)

total_cents
-----------
     371500
(1 row)

Both steps took effect together, and the total is the same as before. (A real bank also adds two ledger rows to transactions in the same transaction.)

BEGIN;
INSERT INTO orders (order_id, customer_id, order_date, status, ship_city)
VALUES (2601, 1, '2026-10-01', 'pending', 'Leeds');
INSERT INTO order_items (order_id, line_no, product_id, quantity, unit_price) VALUES (2601, 1, 2, 2, 44.1);
UPDATE products SET stock = stock - 2 WHERE product_id = 2;
COMMIT;
SELECT COUNT(*) AS lines FROM order_items WHERE order_id = 2601;
SELECT stock FROM products WHERE product_id = 2;
lines
-----
    1
(1 row)

stock
-----
  148
(1 row)

All three steps took effect together: the order has its line, and the stock went down by 2.

BEGIN;
INSERT INTO enrollments (student_id, section_id, enrolled_on) VALUES (1, 31, '2026-01-20');
DELETE FROM enrollments WHERE student_id = 1 AND section_id = 30;
COMMIT;
SELECT student_id, section_id, grade FROM enrollments WHERE student_id = 1 ORDER BY section_id;
student_id  section_id  grade
----------  ----------  -----
         1          19   NULL
         1          31   NULL
         1          41   60.8
(3 rows)

Both steps took effect together: the student is in section 31 and no longer in section 30. (The grade 49.2 belonged to the old enrollment and did not move: the new one has no grade yet.)

Quick check: after a rolled-back transaction, are the changes of its steps kept?

No. A rollback undoes every step of the transaction, so the data is as it was before BEGIN.

Worked example: which jobs need a transaction?

Which of these jobs should be a transaction?

Job Steps Transaction?
Place an order add an order row, add its item rows, reduce stock yes: an order without items, or stock reduced with no order, is wrong
Read today's sales one SELECT not needed for correctness
Change a customer's phone one UPDATE a single statement is already all or nothing
Cancel an order mark it cancelled, return the stock, refund the payment yes: all three or none
Job Steps Transaction?
Transfer money subtract from one account, add to another, write two ledger rows yes: money that vanishes or appears is wrong
Print a statement one SELECT not needed for correctness
Change a customer's city one UPDATE a single statement is already all or nothing
Close an account set the status, cancel its cards, record an audit row yes: all three or none
Job Steps Transaction?
Move a student to another section add the new enrollment, remove the old one yes: otherwise the student is in two sections or in none
Read an attendance list one SELECT not needed for correctness
Change a guardian's name one UPDATE a single statement is already all or nothing
Close a section mark it closed, move its students, notify the teacher yes: all steps or none

Rule of thumb: if a half-finished result would be wrong, put the steps in one transaction. The jobs are made up.

Common mistakes

  • Thinking every program step is safe on its own. The danger is the gap between steps.
  • Making transactions too big. Keep a transaction to the steps that must belong together; long ones hold up other users (lesson 6.6).
  • Forgetting to end a transaction. A transaction left open is neither committed nor rolled back (lesson 6.2).
  • Assuming a single statement needs BEGIN. One UPDATE is already atomic by itself.

Key takeaways

  • Some changes are several steps that must stand or fall together.
  • A transaction groups steps into one unit of work: all or nothing.
  • BEGIN opens it, COMMIT keeps its changes, ROLLBACK throws them away.
  • Use a transaction whenever a half-finished result would be wrong.

Practice

1. In the crash example, what exactly was wrong after the first step?

Show answer

There was an order with no lines, and the stock had not been reduced: the program stopped before the other steps.

Show answer

The first account had been reduced by 200.00 but the program stopped before the second was increased, so the money was subtracted and never added.

Show answer

The student was enrolled in the new section but still in the old one, because the program stopped before removing the old enrollment.

2. What does "all or nothing" mean?

Show answer

Either every step of the transaction takes effect or none does; a half-finished state is never kept.

3. What do BEGIN, COMMIT and ROLLBACK each do?

Show answer

BEGIN starts a transaction, COMMIT makes its changes permanent, ROLLBACK cancels them.

4. Does a single UPDATE statement that changes 1,000 rows need BEGIN to be all or nothing?

Show answer

No. A single SQL statement already succeeds or fails as a whole. You need BEGIN when several statements must belong together.

5. Name a real-life task of yours that has two steps that must both happen.

Show answer

For example, buying a ticket: the seat must be reserved and the payment taken. Taking payment without reserving the seat (or the reverse) would be wrong.

6. Why should a transaction not include steps that do not need to belong together?

Show answer

Longer transactions keep other users waiting longer and make failures undo more work than necessary.