Sub topic 13
Exceptions, Rollback, and Savepoints
Assume you know basic COMMIT, ROLLBACK, and PL/SQL block structure. This chapter focuses on how errors interact with an Oracle transaction.
An exception does not automatically roll back everything
When a SQL statement fails, Oracle rolls back that statement. It does not automatically undo every successful statement that came before it in the transaction.
For example, an update can succeed, a later statement can raise an exception, and the first update can still be pending. The application must decide whether to commit, roll back, or roll back to a savepoint.
A savepoint is a named position inside the current transaction. ROLLBACK TO savepoint_name undoes changes made after that position but keeps earlier changes pending.
BEGIN
UPDATE employees
SET salary = salary * 1.05
WHERE employee_id = 100;
SAVEPOINT after_raise;
BEGIN
UPDATE employees
SET salary = salary * 1.10
WHERE employee_id = 100;
RAISE_APPLICATION_ERROR(-20010, 'Bonus calculation failed');
EXCEPTION
WHEN OTHERS THEN
ROLLBACK TO after_raise;
DBMS_OUTPUT.PUT_LINE('Bonus undone; raise remains pending');
END;
ROLLBACK;
END;
/The first update occurs before the savepoint. The second update occurs after it, so ROLLBACK TO after_raise undoes only the second update. The final ROLLBACK then removes the first update as well. In a real procedure, the caller might commit the first update instead.
How transaction control changes the outcome
A transaction continues until COMMIT or a full ROLLBACK. Rolling back to a savepoint does not end the transaction.
COMMITmakes all pending changes permanent and removes the transaction's savepoints.ROLLBACKremoves all pending changes in the transaction.ROLLBACK TO nameremoves changes after the named savepoint.- A new savepoint with the same name replaces the earlier savepoint with that name.
- DDL statements such as
CREATE TABLEandALTER TABLEcan cause implicit commits.
An exception handler should therefore choose transaction behavior deliberately. A low-level procedure usually should not commit its caller's work unless its contract explicitly requires that behavior.
Transaction flow
Common mistakes
Do not assume that catching an exception commits successful work. Do not use ROLLBACK TO when the requirement is to undo the entire transaction. Also avoid placing COMMIT inside reusable procedures without documenting it, because it can commit changes made by the caller.
When several logical operations share one transaction, create a savepoint before each operation that can be safely reversed. The handler can then undo only the failed operation and let the caller decide what happens next.
Exercise
An update succeeds, a savepoint is created, and a later update fails. Which command undoes only the later update while keeping the earlier update pending?
Show answer
ROLLBACK TO the savepoint name.