Sub topic 11
Transaction control in PL/SQL and exception handling
This chapter assumes you know basic PL/SQL block syntax (BEGIN, EXCEPTION, END) and the SQL transaction statements from earlier chapters: COMMIT, ROLLBACK, and SAVEPOINT. It uses the accounts table from the start of the tutorial.
Blocks are not transactions
A PL/SQL block does not start or end a transaction. A transaction belongs to the session. It begins with the first DML statement after the previous COMMIT or ROLLBACK, and it ends only when something commits or rolls back. A BEGIN ... END pair is just a unit of code.
Reaching END therefore commits nothing. If your block updates rows and ends without a COMMIT, the changes stay pending in the calling session. Conversely, a COMMIT inside a nested procedure commits everything the session has done so far, including work from the caller.
PL/SQL accepts these transaction control statements directly:
| Statement | Effect inside PL/SQL |
|---|---|
| `COMMIT` | Ends the transaction and makes all changes permanent |
| `ROLLBACK` | Ends the transaction and discards all changes |
| `SAVEPOINT name` | Marks a point inside the transaction |
| `ROLLBACK TO SAVEPOINT name` | Undoes work after the savepoint and keeps the transaction open |
| `SET TRANSACTION ...` | Sets isolation or read-only mode, and must be the first statement of the transaction |
| `LOCK TABLE` | Takes a table lock until the transaction ends |
DDL cannot appear directly in PL/SQL. You run it with EXECUTE IMMEDIATE, and it still commits implicitly, as described in the implicit commit chapter.
What happens when an exception is raised
Statement-level atomicity applies to PL/SQL too. When a SQL statement inside a block fails, Oracle undoes that one statement and nothing earlier. The exception then travels up the block structure, and what happens next depends on who catches it.
- A handler catches it. Execution continues in the handler. Work done earlier in the transaction is still pending, and so is any earlier work from the same block. Oracle does not roll anything back for you.
- Nobody catches it. The exception reaches the client. Oracle then rolls back the work of the whole outermost call, to an implicit savepoint taken when the call began. Work committed or done before the call is untouched.
The first case is where most bugs come from. Suppose a procedure runs two updates, the second fails, and the caller catches the exception and carries on. The first update is still part of the open transaction, and a later COMMIT will save it.
Here is the diagram in the required form:
Savepoints inside a loop
A savepoint lets a handler undo exactly one unit of work and keep the rest. This block debits every account by 100. An account that would fall below zero violates the CHECK (balance >= 0) constraint, so it is skipped and the others are still debited.
SET SERVEROUTPUT ON
BEGIN
FOR r IN (SELECT id FROM accounts) LOOP
SAVEPOINT before_row;
BEGIN
UPDATE accounts SET balance = balance - 100 WHERE id = r.id;
EXCEPTION
WHEN OTHERS THEN
ROLLBACK TO SAVEPOINT before_row;
DBMS_OUTPUT.PUT_LINE('Skipped account ' || r.id || ': ' || SQLERRM);
END;
END LOOP;
COMMIT;
END;
/Three details matter here:
- Savepoint names are not scoped to blocks. Executing
SAVEPOINT before_rowagain in the next iteration moves the existing savepoint rather than creating a second one. - A single
UPDATEthat fails is already undone by statement-level atomicity. The savepoint matters when a unit has several statements, because rolling back to it undoes all of them. - The
COMMITcomes after the loop. The whole batch is one business operation, and the per-row savepoints give you partial failure without splitting the transaction.
A procedure that leaves the commit to its caller
A reusable procedure usually should not commit. The caller knows what the full unit of work is. The procedure can still protect its own multi-statement step with a savepoint and re-raise the error.
CREATE OR REPLACE PROCEDURE transfer (
p_from IN NUMBER,
p_to IN NUMBER,
p_amount IN NUMBER
) IS
BEGIN
SAVEPOINT transfer_start;
UPDATE accounts SET balance = balance - p_amount WHERE id = p_from;
IF SQL%ROWCOUNT = 0 THEN
RAISE_APPLICATION_ERROR(-20001, 'Source account not found: ' || p_from);
END IF;
UPDATE accounts SET balance = balance + p_amount WHERE id = p_to;
IF SQL%ROWCOUNT = 0 THEN
RAISE_APPLICATION_ERROR(-20002, 'Target account not found: ' || p_to);
END IF;
EXCEPTION
WHEN OTHERS THEN
ROLLBACK TO SAVEPOINT transfer_start;
RAISE;
END transfer;
/If the target account does not exist, the debit has already happened. The handler rolls back to transfer_start, which undoes the debit, and RAISE passes the original error to the caller. The caller owns the transaction:
BEGIN
transfer(1, 2, 100);
transfer(2, 3, 50);
COMMIT;
EXCEPTION
WHEN OTHERS THEN
ROLLBACK;
RAISE;
END;
/The outer handler rolls back the whole unit, including any transfers that succeeded before the failure.
Handler patterns and pitfalls
Swallowing errors
This handler is a common source of silent data corruption:
EXCEPTION
WHEN OTHERS THEN
NULL;The failing statement is undone, but earlier statements remain pending, and the caller never learns that anything went wrong. A later COMMIT then saves a half-finished unit of work. A WHEN OTHERS handler should do one of two things. It can roll back to a savepoint and re-raise with RAISE. Or it can handle the specific error you expect and continue deliberately.
Rolling back in a handler that re-raises
If a handler ends with RAISE and the error reaches the client uncaught, Oracle rolls back the outermost call anyway. An explicit ROLLBACK in the handler is still useful when the caller might catch the error and continue. It makes the outcome the same either way.
Commits inside loops over a cursor
Committing inside a loop that fetches from a SELECT ... FOR UPDATE cursor ends the transaction and releases the row locks. The next fetch can then fail with ORA-01002: fetch out of sequence. Commit after the loop, or fetch in batches that you control.
Commits that are not allowed
A trigger that fires on DML cannot issue COMMIT or ROLLBACK. It raises ORA-04092. A trigger runs as part of the statement that fired it, and it must succeed or fail together with that statement. A function called from a query has a related restriction. When you need to save something regardless of the outer outcome, such as an audit row, use an autonomous transaction, which a later chapter covers.
Handling expected errors precisely
Prefer named exceptions over WHEN OTHERS where you can. For example, DUP_VAL_ON_INDEX lets you handle a duplicate key while every other error still propagates:
BEGIN
INSERT INTO accounts (id, owner, balance) VALUES (1, 'Alice', 1000);
EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN
UPDATE accounts SET owner = 'Alice' WHERE id = 1;
END;
/Here the failed INSERT is undone by statement atomicity, so the handler starts from a clean state and the UPDATE can run safely.
Guidelines for transaction control in PL/SQL
- Let the code that knows the whole business operation decide when to
COMMIT. This is usually the outermost caller, such as the application or the top-level script. - In a reusable procedure, set a savepoint at its start if it does more than one DML statement, and roll back to it on error before re-raising.
- Re-raise errors you cannot fully resolve. Use
RAISErather thanRAISE_APPLICATION_ERRORwhen you want to keep the original error code and stack. - Avoid
COMMITinside loops except in deliberate batch designs. Frequent commits break the atomicity of the larger operation and make a failed run hard to restart. - Remember that
EXECUTE IMMEDIATEwith DDL commits, even in the middle of your procedure.
Exercises
Exercise
A procedure runs two UPDATE statements. The second one fails with a constraint violation. A caller's WHEN OTHERS handler catches the error, logs it, and then issues COMMIT. Is the first UPDATE saved? Why?
Show answer
Yes. Statement-level atomicity undoes only the failed second UPDATE. Because a handler caught the exception, Oracle did not roll back the rest of the call, so the first UPDATE is still pending in the session's transaction and the COMMIT saves it. To avoid this, set a savepoint at the start of the procedure, roll back to it in the handler, and re-raise, or have the caller ROLLBACK instead of committing.
Exercise
In the loop example with SAVEPOINT beforerow, what happens to the savepoint when the next iteration runs SAVEPOINT beforerow again, and why is the COMMIT placed after END LOOP?
Show answer
Reusing a savepoint name moves the savepoint to the new position, so only one before_row exists at a time and ROLLBACK TO SAVEPOINT always undoes the current row only. The COMMIT is placed after the loop because the whole batch is one unit of work. Committing inside the loop would end the transaction on each row and release its locks, so a later failure could not undo the earlier rows.
Exercise
Why does the transfer procedure end its handler with RAISE instead of just rolling back to the savepoint?
Show answer
Rolling back to the savepoint restores the data, but without RAISE the caller would believe the transfer succeeded. RAISE passes the original exception to the caller, which can then roll back its whole unit of work or report the error.