Database Transactions and ACID · Lesson 42 of 112

Database COMMIT and ROLLBACK

What you will learn

  • What COMMIT and ROLLBACK do
  • What happens when a statement fails inside a transaction
  • How to undo only part of a transaction with a savepoint
  • How Python's sqlite3 opens transactions by itself

This lesson runs on the sample database you chose in lesson 4.1 (use the Example data picker at the top) and changes data in your browser's copy. Run the examples from top to bottom; Reset data starts again.

1. Ending a transaction

A transaction ends in exactly one of two ways:

Command Effect
COMMIT all changes become permanent and visible to others
ROLLBACK all changes since BEGIN are discarded

2. When a statement fails

A rule of the table can refuse a step. Inside a transaction, the failed statement is reported, but the transaction stays open: the program must end it.

Account 5 holds 1,531.00. Sending 3,000.00 would make its balance negative, and the column has the rule CHECK (balance_cents >= 0):

BEGIN;
(done)
UPDATE accounts SET balance_cents = balance_cents - 300000 WHERE account_id = 5;
IntegrityError: CHECK constraint failed: balance_cents >= 0

A customer orders a product, but the order needs more than the stock has. The column has the rule CHECK (stock >= 0):

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, 4, 100, 5.4);
(1 row changed)

Product 4 has 40 in stock; the order wants 100:

UPDATE products SET stock = stock - 100 WHERE product_id = 4;
IntegrityError: CHECK constraint failed: stock >= 0

A teacher enters a grade. The column has the rule CHECK (grade BETWEEN 0 AND 100):

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

The second step is a typing mistake, a grade of 120:

UPDATE enrollments SET grade = 120 WHERE student_id = 1 AND section_id = 31;
IntegrityError: CHECK constraint failed: grade BETWEEN 0 AND 100

The rule refused the statement with an error. The transaction was still open: you can prove it, because ROLLBACK works now, and it would fail if no transaction were open.

ROLLBACK;
SELECT account_id, balance_cents FROM accounts WHERE account_id = 5;
account_id  balance_cents
----------  -------------
         5         153100
(1 row)

A second ROLLBACK has nothing to end:

ROLLBACK;
OperationalError: cannot rollback - no transaction is active
ROLLBACK;
SELECT COUNT(*) AS lines FROM order_items WHERE order_id = 2601;
SELECT stock FROM products WHERE product_id = 4;
lines
-----
    0
(1 row)

stock
-----
   40
(1 row)

A second ROLLBACK has nothing to end:

ROLLBACK;
OperationalError: cannot rollback - no transaction is active
ROLLBACK;
SELECT student_id, section_id FROM enrollments WHERE student_id = 1 ORDER BY section_id;
student_id  section_id
----------  ----------
         1          19
         1          30
         1          41
(3 rows)

A second ROLLBACK has nothing to end:

ROLLBACK;
OperationalError: cannot rollback - no transaction is active

The first ROLLBACK ended the open transaction, and everything since BEGIN is gone (the balance, the stock and the enrollments are as they were). The second one is refused, because no transaction is active any more. Good programs always have a plan for the failure path: roll back and report the error.

3. Savepoints: undoing part of a transaction

A savepoint is a named mark inside a transaction. ROLLBACK TO goes back to the mark without cancelling the whole transaction. The work before the mark is kept, and the transaction stays open until you COMMIT.

Change a customer's city, then try an optional step (closing their accounts) and undo only that step:

BEGIN;
UPDATE customers SET city = 'Lisbon' WHERE customer_id = 77;
SAVEPOINT s1;
UPDATE accounts SET status = 'closed' WHERE customer_id = 77;
SELECT account_id, status FROM accounts WHERE customer_id = 77 ORDER BY account_id;
ROLLBACK TO s1;
COMMIT;
SELECT account_id, status FROM accounts WHERE customer_id = 77 ORDER BY account_id;
SELECT customer_id, city FROM customers WHERE customer_id = 77;
account_id  status
----------  ------
         1  closed
       425  closed
(2 rows)

account_id  status
----------  ------
         1  open
       425  open
(2 rows)

customer_id  city
-----------  ------
         77  Lisbon
(1 row)

Change a customer's phone number, then try an optional step (hiding a product) and undo only that step:

BEGIN;
UPDATE customers SET phone = '+44 20000000' WHERE customer_id = 1;
SAVEPOINT s1;
UPDATE products SET is_active = 0 WHERE product_id = 2;
SELECT product_id, name, is_active FROM products WHERE product_id = 2;
ROLLBACK TO s1;
COMMIT;
SELECT product_id, name, is_active FROM products WHERE product_id = 2;
SELECT customer_id, phone FROM customers WHERE customer_id = 1;
product_id  name         is_active
----------  -----------  ---------
         2  Ceramic mug          0
(1 row)

product_id  name         is_active
----------  -----------  ---------
         2  Ceramic mug          1
(1 row)

customer_id  phone
-----------  ------------
          1  +44 20000000
(1 row)

Change a guardian's name, then try an optional step (dropping an enrollment) and undo only that step:

BEGIN;
UPDATE students SET guardian_name = 'Not given' WHERE student_id = 1;
SAVEPOINT s1;
DELETE FROM enrollments WHERE student_id = 1 AND section_id = 41;
SELECT student_id, section_id FROM enrollments WHERE student_id = 1 ORDER BY section_id;
ROLLBACK TO s1;
COMMIT;
SELECT student_id, section_id FROM enrollments WHERE student_id = 1 ORDER BY section_id;
SELECT student_id, guardian_name FROM students WHERE student_id = 1;
student_id  section_id
----------  ----------
         1          19
         1          30
(2 rows)

student_id  section_id
----------  ----------
         1          19
         1          30
         1          41
(3 rows)

student_id  guardian_name
----------  -------------
         1  Not given
(1 row)

The first table shows the optional step done inside the transaction; the later tables show that only that step was undone: the first change was committed, the second was not. Savepoints are useful when one optional step of a bigger job may fail and the rest should still go ahead.

4. How Python's sqlite3 starts transactions

This part is about the Python module, not about SQL, so it stays in Python. In its normal mode (without isolation_level=None), Python opens a transaction for you before the first INSERT, UPDATE or DELETE, and leaves it open until you call commit() or rollback():

import sqlite3

c2 = sqlite3.connect(":memory:")
c2.execute("CREATE TABLE t (x)")
print("in_transaction after create:", c2.in_transaction)
c2.execute("INSERT INTO t VALUES (1)")
print("after insert:", c2.in_transaction)
c2.rollback()
print(c2.execute("SELECT COUNT(*) FROM t").fetchone(), c2.in_transaction)
c2.execute("INSERT INTO t VALUES (1)")
c2.commit()
print(c2.execute("SELECT COUNT(*) FROM t").fetchone())
in_transaction after create: False
after insert: True
(0,) False
(1,)

The first insert was rolled back (count 0); the second was committed (count 1). If you forget commit(), your changes are lost when the connection closes. That is the most common beginner surprise with sqlite3. (Since Python 3.12 you can also pass autocommit=False to sqlite3.connect(): a transaction is then always open, and you must commit or roll back explicitly. This lesson describes the default mode.)

Worked example: reading the failure path

A program runs: BEGIN; insert an order; insert 3 item rows; the third item violates a rule and raises an error.

Step State
after BEGIN nothing changed yet
order and 2 items inserted visible only inside this transaction
third item fails the transaction is still open
program runs ROLLBACK order and 2 items disappear

Without the ROLLBACK the order would stay half-built inside an open transaction. The program should roll back, tell the user, and let them try again.

Common mistakes

  • Never calling commit() in Python, then wondering where the data went.
  • Catching the error and carrying on without rolling back.
  • Leaving a transaction open while waiting for a user to type something.
  • Mixing up ROLLBACK and ROLLBACK TO: the first cancels the whole transaction; the second goes back only to a savepoint, and the transaction stays open.

Key takeaways

  • A transaction ends with COMMIT (keep) or ROLLBACK (discard).
  • A failed statement does not end the transaction for you; the program must decide.
  • A savepoint lets you undo part of a transaction.
  • Python's sqlite3 opens transactions automatically for data changes; you must call commit().

Practice

1. After ROLLBACK, what is the data like?

Show answer

Exactly as it was before BEGIN.

2. In the failing example, why could you still run ROLLBACK after the error?

Show answer

An error in one statement does not close the transaction; the program must run ROLLBACK or COMMIT. A second ROLLBACK failed because the first had already ended the transaction.

3. What is the difference between ROLLBACK and ROLLBACK TO s1?

Show answer

ROLLBACK cancels the whole transaction; ROLLBACK TO s1 undoes only the changes made after the savepoint, and the transaction remains open.

4. A Python program inserts a row but never calls commit() and then closes. Is the row saved?

Show answer

No. The open transaction is discarded when the connection closes.

5. When might you use a savepoint?

Show answer

When one optional step in a bigger job may fail and you want to undo just that step while keeping the rest, for example adding a bonus item to an order.

6. Why is it bad to leave a transaction open while waiting for the user to type?

Show answer

The user may take minutes, and during that time the transaction can hold locks that block other users (lesson 6.6).