Sub topic 4
Undoing Changes with ROLLBACK
This chapter assumes you know basic INSERT, UPDATE, and DELETE statements and can connect to Oracle with SQL*Plus, SQL Developer, or SQLcl. You will use ROLLBACK to discard changes that have not been committed.
What ROLLBACK Does
ROLLBACK ends the current transaction and reverses its uncommitted changes. Oracle restores the affected rows to their values from before the transaction began.
For example:
UPDATE accounts
SET balance = balance - 100
WHERE id = 1;
UPDATE accounts
SET balance = balance + 100
WHERE id = 2;
-- Discover that the transfer should not happen
ROLLBACK;Both updates are undone. The balances return to their previous values, and the row locks held by this transaction are released. A later session can then update those rows.
A rollback cannot undo changes that were already committed. It also cannot undo a data definition language statement, such as CREATE TABLE, after Oracle has performed its implicit commit.
Rollback Ends the Transaction
A full rollback ends the current transaction in the same way that COMMIT does. The next data manipulation statement begins a new transaction.
A rollback is useful when validation fails, a business rule is not satisfied, or an application catches an error and decides that no part of the unit of work should remain.
Rolling Back to a Savepoint
A savepoint marks a position inside an open transaction. ROLLBACK TO SAVEPOINT reverses work done after that point but keeps the earlier work and the transaction itself.
INSERT INTO accounts (id, owner, balance)
VALUES (3, 'Carol', 500);
SAVEPOINT after_carol;
UPDATE accounts
SET balance = balance - 50
WHERE id = 3;
DELETE FROM accounts
WHERE id = 1;
ROLLBACK TO SAVEPOINT after_carol;
COMMIT;The update and delete are undone. Carol's inserted row remains and is committed. The rollback to the savepoint does not end the transaction, so the session can continue issuing statements.
When Oracle rolls back to a savepoint, savepoints created after that savepoint are erased. A savepoint created before it remains available. Locks acquired after the savepoint are generally released, while locks acquired earlier remain held.
Common Errors
- Expecting
ROLLBACKto undo a previousCOMMIT. - Issuing DDL before rollback and assuming the earlier DML is still reversible.
- Using
ROLLBACK TO SAVEPOINTand assuming the transaction has ended. - Forgetting to commit or fully roll back before returning a database connection to a connection pool.
- Assuming a failed SQL statement automatically rolls back all earlier statements in the transaction. Oracle normally rolls back the failed statement, not the entire transaction.
Exercise
An uncommitted transaction inserts a row, creates a savepoint, updates that row, and then runs ROLLBACK TO SAVEPOINT. What remains in the transaction?
Show answer
The inserted row remains, the update is undone, and the transaction stays open until COMMIT or a full ROLLBACK.