Skip to main content

ROLLBACK

ROLLBACK undoes all pending changes in the current transaction.

Use it when validation fails, an error occurs, or you need to abandon an operation.

Core Concepts

flowchart TD
A[BEGIN] --> B[Pending writes]
B --> C{Success?}
C -->|No| D[ROLLBACK]
D --> E[Database restored to pre-transaction state]
CommandEffect
ROLLBACK;Cancels all pending transaction writes
COMMIT;Finalizes all pending transaction writes

Code Examples

-- Setup rollback demo table.
CREATE TABLE tx_rollback_demo (
id INTEGER PRIMARY KEY,
value TEXT NOT NULL
);
Expected output
Demo table created.
-- Start transaction and insert two rows.
BEGIN;

INSERT INTO tx_rollback_demo (value)
VALUES ('temp-1'), ('temp-2');

-- Abort all pending writes.
ROLLBACK;
Expected output
Pending inserts are discarded.
-- Verify table remains unchanged.
SELECT COUNT(*) AS row_count
FROM tx_rollback_demo;
row_count
0

SQLite-Specific Nuances

SQLite Nuance

ROLLBACK affects the current open transaction scope in the active connection.

If no transaction is active, rollback behavior is effectively a no-op/error context depending on state.

Common Pitfalls / Best Practices

Pitfall

Catching an error in application code but forgetting to issue ROLLBACK, leaving the transaction open.

Best Practice

In application code, pair transaction logic with guaranteed rollback paths (for example, try/catch/finally).

Quick Challenge

Insert one row into tx_rollback_demo and then intentionally roll it back.

View Solution
BEGIN;

INSERT INTO tx_rollback_demo (value)
VALUES ('will-not-persist');

ROLLBACK;
Expected output
Inserted row does not persist after rollback.