Sub topic 13
Exceptions, rollback, and savepoints
This chapter assumes you can write a block with an EXCEPTION section, you know COMMIT and ROLLBACK, and you have seen RAISE and RAISE_APPLICATION_ERROR. It covers what an error does to uncommitted data, and how to use a savepoint to undo only part of a transaction.
What Oracle undoes for you
An exception does not roll back a transaction. Oracle applies two narrower rules.
- Statement-level atomicity. If a single SQL statement fails, Oracle undoes everything that statement changed. An
UPDATEthat fails on row 500 leaves rows 1 to 499 unchanged. - Unhandled exceptions. If an exception leaves the outermost block or call without being handled, Oracle undoes the changes made by that failed call. Work done earlier in the same transaction stays, and the client decides whether to commit or roll back.
A handled exception triggers neither rule, apart from the failing statement itself. Changes made by earlier statements in the block remain in the transaction, and so do changes made by subprograms that completed before the error.
The partial-update problem
The examples use a small table. Run this setup first, and run SET SERVEROUTPUT ON in SQL*Plus or SQLcl to see the output.
CREATE TABLE accounts (
account_id NUMBER PRIMARY KEY,
balance NUMBER NOT NULL CHECK (balance >= 0)
);
INSERT INTO accounts VALUES (1, 100);
INSERT INTO accounts VALUES (2, 50);
COMMIT;The next block adds 80 to account 1 and then tries to take 80 from account 2, which only holds 50. The second statement violates the check constraint, and the handler swallows the error.
BEGIN
UPDATE accounts SET balance = balance + 80 WHERE account_id = 1;
UPDATE accounts SET balance = balance - 80 WHERE account_id = 2;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Error: ' || SQLERRM);
END;
/
SELECT account_id, balance FROM accounts ORDER BY account_id;The handler prints an ORA-02290 message. The query then shows account 1 with a balance of 180 and account 2 with 50. The failed statement was undone, but the first UPDATE was not, so money has been created. Undo it with ROLLBACK; before continuing.
The block looks safe because it handles the error. The problem is that the handler neither rolls back nor re-raises.
Savepoints
A savepoint is a named marker inside the current transaction. ROLLBACK TO name undoes everything done after the marker. It leaves earlier work in place, and the transaction stays open.
SAVEPOINT name;marks the current position. You do not declare the name.ROLLBACK TO name;undoes changes made after the marker and releases row locks taken after it. The savepoint itself stays defined.- Executing
SAVEPOINTagain with the same name moves the marker to the new position. COMMITand a fullROLLBACKerase all savepoints in the transaction.
Savepoints belong to the transaction, not to the block that created them. A savepoint set in one procedure is visible to every procedure that runs later in the same transaction.
A subprogram that cleans up after itself
A subprogram that changes several rows should leave the data as it found it if it fails. The usual pattern is to set a savepoint on entry, roll back to it in the handler, and then re-raise the error. The caller's earlier work is not touched.
CREATE OR REPLACE PROCEDURE transfer (
p_from IN accounts.account_id%TYPE,
p_to IN accounts.account_id%TYPE,
p_amount IN NUMBER
) IS
BEGIN
SAVEPOINT before_transfer;
UPDATE accounts
SET balance = balance - p_amount
WHERE account_id = p_from;
IF SQL%NOTFOUND THEN
RAISE_APPLICATION_ERROR(-20010, 'Source account not found');
END IF;
UPDATE accounts
SET balance = balance + p_amount
WHERE account_id = p_to;
IF SQL%NOTFOUND THEN
RAISE_APPLICATION_ERROR(-20011, 'Target account not found');
END IF;
EXCEPTION
WHEN OTHERS THEN
ROLLBACK TO before_transfer;
RAISE;
END transfer;
/The caller below makes its own change first. It then calls transfer with a target account that does not exist, so the debit succeeds and the credit fails.
BEGIN
UPDATE accounts SET balance = balance + 1 WHERE account_id = 2;
BEGIN
transfer(1, 99, 30);
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Transfer failed: ' || SQLERRM);
END;
END;
/
SELECT account_id, balance FROM accounts ORDER BY account_id;
ROLLBACK;The message is ORA-20011: Target account not found. Account 1 still holds 100, because the handler undid the debit. Account 2 holds 51, because the caller's own update came before the savepoint and survives. Without the savepoint, account 1 would hold 70.
The handler calls RAISE, not RAISE_APPLICATION_ERROR. This keeps the original error code and the original message, as covered in the chapter on re-raising.
Rules for transaction control in handlers
- Roll back to a savepoint, not the whole transaction. A plain
ROLLBACKinside a subprogram also discards the caller's uncommitted work, which the caller did not agree to. - Do not commit in a handler. Leave
COMMITto the code that owns the transaction. A commit also erases your savepoints. A laterROLLBACK TOthen fails with ORA-01086 (savepoint never established or no longer valid). - Know that DDL commits.
CREATE,ALTER, andDROPstatements issue an implicit commit, so a savepoint set before one of them is gone afterward. - Choose savepoint names with care. Setting a savepoint with a name already in use in the same transaction moves it. A recursive procedure or two procedures that share a name can therefore overwrite each other's marker. Use a name specific to the procedure.
- Re-raise unless you have truly recovered. If the handler rolls back and then returns normally, the caller sees success even though the work was undone.
Using a savepoint to skip a failed step
A savepoint is also useful when you want to continue after a failure. In this loop, each employee's update is attempted separately. If one fails, only that employee's changes are undone, and the loop moves on. This assumes the HR sample schema, as in the earlier chapters.
BEGIN
FOR r IN (SELECT employee_id FROM employees WHERE department_id = 50) LOOP
SAVEPOINT before_employee;
BEGIN
raise_salary(r.employee_id, -5);
EXCEPTION
WHEN OTHERS THEN
ROLLBACK TO before_employee;
DBMS_OUTPUT.PUT_LINE('Skipped ' || r.employee_id || ': ' || SQLERRM);
END;
END LOOP;
END;
/Each pass through the loop moves before_employee forward, so a rollback only reaches back to the current employee. The raise_salary procedure comes from an earlier chapter. It rejects the negative percentage with ORA-20001, so every employee is skipped here. Change -5 to 5 to see the successful path.
The script does not commit, so it leaves the final decision to whoever runs it.
Summary of behaviors
| Situation | Effect on data |
|---|---|
| A single SQL statement fails | That statement's changes are undone |
| Exception unhandled at the top level | The failed call is undone, earlier transaction work remains |
| Exception handled, no rollback | Earlier statements in the block stay in the transaction |
| `ROLLBACK TO name` in a handler | Work after the savepoint is undone, the transaction stays open |
| `ROLLBACK` in a handler | The whole transaction is undone, including the caller's work |
| `COMMIT` before the error | The committed work is permanent, and savepoints are lost |
Exercise
A procedure runs INSERT A, then INSERT B, then INSERT C, which fails with a constraint error. The procedure has EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE(SQLERRM); and nothing else. After the call returns, which inserts are part of the open transaction?
Show answer
INSERT A and INSERT B. Statement-level atomicity undoes only INSERT C. The handler neither rolls back nor re-raises, so the procedure returns normally and the first two inserts stay in the transaction. Adding a savepoint at the start, ROLLBACK TO in the handler, and RAISE would undo all three and report the failure.
Exercise
A procedure sets SAVEPOINT s1, does some updates, calls COMMIT, and later in its handler runs ROLLBACK TO s1. What happens, and why?
Show answer
The handler raises ORA-01086 (savepoint 's1' never established in this session or is invalid). COMMIT ends the transaction and erases all its savepoints, so s1 no longer exists. The fix is to avoid committing inside the procedure, or to set a new savepoint after the commit.