Concept · Modifying data

ROLLBACK

ROLLBACK undoes every change in the transaction in progress and ends it without committing them. It cannot undo a transaction that has already ended with COMMIT.

Before continuing: This entry is part of the transactions guide. If you are new to the topic, start with BEGIN / START TRANSACTION.

ROLLBACK example

The keyboard starts with 7 units in stock. The transaction below temporarily reduces the stock by 2, checks the value and then undoes the change:

SQL
BEGIN;

UPDATE products
SET stock = stock - 2
WHERE id = 2;

SELECT stock AS stock_during_transaction
FROM products
WHERE id = 2;

ROLLBACK;

SELECT stock AS final_stock
FROM products
WHERE id = 2;

Inside the transaction the stock drops to 5. After ROLLBACK, the final query shows 7 again because the change was never committed.

Check the result with small data

We insert a row but cancel the transaction before committing it.

Self-contained test · SQLite
CREATE TABLE demo_cancel (id INTEGER PRIMARY KEY);
BEGIN;
INSERT INTO demo_cancel VALUES (1);
ROLLBACK;
SELECT COUNT(*) AS saved_rows FROM demo_cancel;
Check result
saved_rows
0

After ROLLBACK, the table is still empty. Transactions help you avoid leaving half-finished changes behind when an operation fails.

Check your understanding: What would the count show if you ran COMMIT instead of ROLLBACK?

Show answer

1. COMMIT would confirm the insert and the count would show one stored row.

How ROLLBACK is used

ROLLBACK is not a backup. It can only cancel changes that still belong to an open transaction. Once you have committed, you need other recovery mechanisms.

Common mix-ups with ROLLBACK

Expecting ROLLBACK to undo a COMMIT

COMMIT closes the transaction and commits its changes. After COMMIT, a ROLLBACK cannot revert changes that are already committed; if no transaction is active, the exact behaviour or message depends on the engine and the tool. Before committing, check the number of rows and a few representative values.

Key differences between engines

ROLLBACK is part of everyday transaction control, but how a transaction starts and how autocommit works vary between tools and engines. Some data definition statements also have special rules. Practise on a test database first.

To undo only part of the work without abandoning the whole transaction, look at savepoints and ROLLBACK TO SAVEPOINT.