Sub topic 11
Transactions Inside Triggers: No COMMIT and Autonomous Transactions
This chapter assumes you can write row-level triggers with :OLD and :NEW, and that you know how COMMIT, ROLLBACK, and savepoints work in a session. It covers why a trigger cannot end a transaction, what that means for audit rows, and how an autonomous transaction lets a trigger write data that survives a rollback.
A Trigger Is Part of the Statement That Fired It
A trigger does not run in a transaction of its own. When an UPDATE fires a trigger, the trigger's SQL runs inside the same transaction as that UPDATE. Everything the trigger writes is committed or rolled back together with the triggering change.
This is the main reason audit triggers are reliable. If the user rolls back, the audit row disappears with the change it describes. If the statement fails, Oracle undoes the statement and any work its triggers did.
The consequence is a hard rule. A trigger may not end the transaction it belongs to. The caller decides when to commit, and a trigger cannot take that decision away.
What Is Not Allowed
These statements are rejected inside a trigger body:
| Statement | Result |
|---|---|
| `COMMIT` | ORA-04092: cannot COMMIT in a trigger |
| `ROLLBACK` | ORA-04092: cannot ROLLBACK in a trigger |
| `SAVEPOINT`, `ROLLBACK TO SAVEPOINT` | ORA-04092 |
| DDL such as `CREATE TABLE` or `TRUNCATE` | ORA-04092, because DDL commits implicitly |
The errors appear at run time, not when the trigger is created. This trigger compiles without errors:
CREATE OR REPLACE TRIGGER employees_bad_commit
AFTER INSERT ON employees
FOR EACH ROW
BEGIN
INSERT INTO employee_audit
(employee_id, action, new_salary, changed_by, changed_at)
VALUES
(:NEW.employee_id, 'INSERT', :NEW.salary,
SYS_CONTEXT('USERENV', 'SESSION_USER'), SYSTIMESTAMP);
COMMIT; -- fails at run time
END employees_bad_commit;
/The first INSERT INTO employees that fires it fails with ORA-04092, and the insert is undone. Remove the COMMIT and the trigger works as intended.
Two exceptions exist. A trigger can commit if the work happens in an autonomous transaction (covered below). System event triggers such as AFTER LOGON are also not bound by the same rule, because no user transaction is in progress when they run.
Statement Failure and Trigger Work
If a trigger raises an unhandled exception, Oracle rolls back the whole triggering statement. That includes changes made by the statement itself and by every trigger it fired. Earlier statements in the same transaction stay intact.
This is how the salary check from the earlier chapter blocks a change. RAISE_APPLICATION_ERROR fails the UPDATE, and no row changes.
The side effect appears when you want to record that the failure happened. A plain INSERT into a log table, made just before the RAISE_APPLICATION_ERROR, is rolled back along with the statement. The log row never survives.
-- This logs nothing that lasts: the INSERT is undone with the failed UPDATE.
CREATE OR REPLACE TRIGGER employees_salary_chk_bad
BEFORE UPDATE OF salary ON employees
FOR EACH ROW
WHEN (NEW.salary < OLD.salary)
BEGIN
INSERT INTO salary_attempt_log
(employee_id, old_salary, new_salary, attempted_by, attempted_at)
VALUES
(:OLD.employee_id, :OLD.salary, :NEW.salary,
SYS_CONTEXT('USERENV', 'SESSION_USER'), SYSTIMESTAMP);
RAISE_APPLICATION_ERROR(-20001, 'Salary cannot be decreased');
END employees_salary_chk_bad;
/Autonomous Transactions
An autonomous transaction is an independent transaction started from inside another one. You declare it with PRAGMA AUTONOMOUS_TRANSACTION. The calling transaction is suspended, the autonomous block runs and commits or rolls back on its own, and then control returns to the caller.
Because that fence has to follow the format rules, here is the diagram in the required form.
The cleanest pattern puts the pragma in a small stand-alone procedure and calls it from the trigger. The trigger stays simple, and the autonomous scope is as small as possible.
CREATE TABLE salary_attempt_log (
employee_id NUMBER,
old_salary NUMBER,
new_salary NUMBER,
attempted_by VARCHAR2(128),
attempted_at TIMESTAMP
);
CREATE OR REPLACE PROCEDURE log_salary_attempt (
p_employee_id IN NUMBER,
p_old_salary IN NUMBER,
p_new_salary IN NUMBER
) IS
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
INSERT INTO salary_attempt_log
(employee_id, old_salary, new_salary, attempted_by, attempted_at)
VALUES
(p_employee_id, p_old_salary, p_new_salary,
SYS_CONTEXT('USERENV', 'SESSION_USER'), SYSTIMESTAMP);
COMMIT;
EXCEPTION
WHEN OTHERS THEN
ROLLBACK;
RAISE;
END log_salary_attempt;
/
CREATE OR REPLACE TRIGGER employees_salary_chk
BEFORE UPDATE OF salary ON employees
FOR EACH ROW
WHEN (NEW.salary < OLD.salary)
BEGIN
log_salary_attempt(:OLD.employee_id, :OLD.salary, :NEW.salary);
RAISE_APPLICATION_ERROR(-20001, 'Salary cannot be decreased');
END employees_salary_chk;
/To check the behavior, run an update that the trigger rejects, then roll back and count the log rows:
UPDATE employees SET salary = salary - 100 WHERE employee_id = 100;
-- ORA-20001: Salary cannot be decreased
ROLLBACK;
SELECT COUNT(*) FROM salary_attempt_log WHERE employee_id = 100;
-- 1 or more: the log row was committed independentlyYou can also put the pragma on the trigger itself, and then the trigger body may commit. This is allowed, but it makes the whole trigger autonomous. That includes any validation logic, which is rarely what you want. Prefer the procedure.
Rules for Autonomous Blocks
An autonomous block must end its transaction before it returns. If it leaves uncommitted changes behind, Oracle raises ORA-06519: active autonomous transaction detected and rolled back. Every code path, including the exception handler, needs a COMMIT or ROLLBACK. The procedure above does this.
The autonomous transaction is a different transaction, so it has these properties:
- It cannot see the caller's uncommitted changes. A query inside it reads the data as last committed.
- It does not share locks with the caller. If it tries to update a row the caller has locked, the session waits on itself and Oracle reports ORA-00060 (deadlock detected).
- Its commit does not commit the caller's work, and the caller's rollback does not undo it.
Edge Cases and Hazards
The independence that makes autonomous logging useful also causes bugs.
- Duplicate side effects. Oracle can restart an
UPDATEorDELETEinternally to keep it read-consistent, and the triggers fire again on the restart. Rolled-back work disappears, but an autonomous commit does not. A restarted statement can leave several log rows for one logical change. - Logs for changes that never happen. A BEFORE trigger may log a change, and a later constraint violation or another trigger may then fail the statement. The committed log row describes a change that never occurred. That suits "attempt" logs but is wrong for an audit trail of real changes. Real change audits belong in a normal, non-autonomous AFTER trigger.
- Not a fix for ORA-04091. An autonomous block can query the table that is mutating, because it sees only committed data. The result ignores the changes made by the current statement, so it is often wrong. Use a compound trigger for that problem, as the following chapters show.
- Cost. Each autonomous commit forces a log write. Calling one per row in a bulk update slows the statement noticeably.
Exercise
A BEFORE UPDATE row trigger inserts a row into a log table and then raises an exception with RAISEAPPLICATIONERROR. The log insert is a normal INSERT in the trigger body. After the failed UPDATE, the log table is empty. Why, and what minimal change makes the log row survive?
Show answer
The log INSERT runs in the same transaction as the UPDATE. When the trigger raises an unhandled exception, Oracle rolls back the whole triggering statement, including the trigger's INSERT. To keep the row, move the INSERT into a procedure declared with PRAGMA AUTONOMOUSTRANSACTION that commits before returning, and call that procedure from the trigger before the RAISEAPPLICATION_ERROR. The procedure's commit is independent of the caller's rollback.
Exercise
An autonomous procedure called from a trigger inserts a row but has no COMMIT or ROLLBACK on the success path. What error do you get, and what must every code path do?
Show answer
Oracle raises ORA-06519: active autonomous transaction detected and rolled back. Every code path in an autonomous block, including exception handlers, must end with a COMMIT or ROLLBACK before the block returns.