Sub topic 12
Autonomous transactions for logging and auditing
An autonomous transaction is a transaction that runs inside a PL/SQL subprogram but commits or rolls back independently of the transaction that called it. Its main use is logging and auditing, where a record must survive even when the business transaction fails and is rolled back.
This chapter assumes you know COMMIT, ROLLBACK, and savepoints, and that you can read basic PL/SQL blocks and exception handlers. It uses the accounts table from earlier chapters.
The problem: a log that disappears with the rollback
Suppose a transfer procedure writes a log row, then fails and rolls back. The log row is part of the same transaction, so the ROLLBACK removes it too. The log then shows only the successes, which is the opposite of what an audit trail should do.
You cannot fix this by calling COMMIT in the middle of the transfer. That would also make the half-finished transfer permanent, and it would destroy the ability to roll back. You need a second, separate transaction that commits only the log row.
Declaring an autonomous transaction
Add PRAGMA AUTONOMOUS_TRANSACTION; to the declaration section of a subprogram. A pragma is a compiler directive. This one tells Oracle to run the subprogram in its own transaction.
CREATE TABLE audit_log (
id NUMBER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
msg VARCHAR2(200),
logged_at TIMESTAMP DEFAULT SYSTIMESTAMP
);
CREATE OR REPLACE PROCEDURE log_msg(p_msg IN VARCHAR2) IS
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
INSERT INTO audit_log (msg) VALUES (p_msg);
COMMIT;
END log_msg;
/When a caller invokes log_msg, Oracle takes these steps:
- It suspends the caller's transaction. The caller's uncommitted changes and locks stay in place.
- It starts a new, independent transaction for the body of
log_msg. - The body runs. Its COMMIT affects only the new transaction.
- When the procedure returns, the caller's transaction resumes exactly where it was.
Using it in a transfer
The block below tries to move 5000 out of Alice's account. The CHECK (balance >= 0) constraint makes the UPDATE fail. The handler logs the failure through the autonomous procedure, rolls back, and re-raises the error. This assumes Alice's balance is less than 5000.
SET SERVEROUTPUT ON
DECLARE
v_err VARCHAR2(200);
BEGIN
log_msg('Transfer started: 1 -> 2, amount 5000');
UPDATE accounts SET balance = balance - 5000 WHERE id = 1;
UPDATE accounts SET balance = balance + 5000 WHERE id = 2;
log_msg('Transfer succeeded');
COMMIT;
EXCEPTION
WHEN OTHERS THEN
v_err := SUBSTR(SQLERRM, 1, 150);
ROLLBACK;
log_msg('Transfer failed: ' || v_err);
RAISE;
END;
/
SELECT msg FROM audit_log ORDER BY id;The block ends with the ORA-02290 error propagating to the caller, and the account balances are unchanged. The final query still returns both log rows: "Transfer started" and "Transfer failed: ORA-02290 ...". The ROLLBACK undid only the main transaction.
The handler captures SQLERRM into a variable before doing anything else. Any later SQL or PL/SQL call can overwrite the error information, and a variable is a safe copy.
Rules the autonomous transaction must follow
It must end with COMMIT or ROLLBACK
An autonomous block cannot return with its transaction still open. If you forget the COMMIT, Oracle raises ORA-06519 ("active autonomous transaction detected and rolled back"). The error also rolls back the work.
CREATE OR REPLACE PROCEDURE log_broken(p_msg IN VARCHAR2) IS
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
INSERT INTO audit_log (msg) VALUES (p_msg);
-- no COMMIT or ROLLBACK: calling this raises ORA-06519
END log_broken;
/It does not see the caller's uncommitted data
The autonomous transaction is a different transaction, so under the default READ COMMITTED level it behaves like another session. It sees only committed data. If the caller inserts a row and then calls an autonomous procedure that selects that row, the procedure finds nothing.
It can deadlock with its own caller
The caller is suspended, but it still holds its row locks. If the autonomous code tries to change a row the caller has locked, it waits for a lock that cannot be released until it finishes. Oracle detects this and raises ORA-00060 (deadlock detected) in the autonomous transaction. The rule: keep autonomous code to tables the caller does not modify, such as log tables.
CREATE OR REPLACE PROCEDURE touch_account(p_id IN NUMBER) IS
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
UPDATE accounts SET balance = balance WHERE id = p_id;
COMMIT;
END touch_account;
/
BEGIN
UPDATE accounts SET balance = balance + 1 WHERE id = 2; -- caller locks row 2
touch_account(2); -- ORA-00060
END;
/Its changes are permanent whatever the caller does
This is the purpose of the feature, and it is also the risk. If the caller later rolls back, the autonomous work stays. Do not use autonomous transactions for changes that must be undone together with the main work.
Where the pragma can go
| Location | Allowed |
|---|---|
| Standalone procedure or function | Yes |
| Procedure or function in a package body | Yes, per subprogram |
| Local subprogram inside a block | Yes |
| Top-level anonymous block | Yes |
| Method of an object type | Yes |
| Database trigger | Yes |
| A whole package at once | No |
The pragma applies to one subprogram, not to the package that contains it. Every subprogram that needs its own transaction must declare it.
Auditing with triggers
Autonomous transactions are useful in triggers. A trigger normally cannot commit, because it runs inside the triggering statement's transaction. If the trigger calls an autonomous procedure such as log_msg, the log entry commits on its own. This lets you record attempted changes even when the statement later fails or the user rolls back.
Be careful with this pattern. A trigger on a busy table that writes an autonomous commit for every row adds one commit per affected row, and that is slow. A bulk UPDATE of 100,000 rows would produce 100,000 commits. Also remember that the audit row records an attempt. The change may never become permanent, so the log must say so in its wording.
Making the logger itself safe
If log_msg fails, for example because audit_log is full or the message is too long, its error propagates into the business code. The failure then masks the original problem inside an exception handler. A logger can instead swallow its own errors:
CREATE OR REPLACE PROCEDURE log_msg_safe(p_msg IN VARCHAR2) IS
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
INSERT INTO audit_log (msg) VALUES (SUBSTR(p_msg, 1, 200));
COMMIT;
EXCEPTION
WHEN OTHERS THEN
ROLLBACK; -- the autonomous transaction must still end cleanly
END log_msg_safe;
/This version truncates the text to the column size and always ends its transaction. The trade-off is that a broken logger fails silently. For audit requirements that must never lose a record, let the error propagate and handle it deliberately.
Common mistakes
- Using it to skip proper design. Wrapping ordinary business updates in autonomous transactions to "make them stick" breaks atomicity. A failed order could leave half of its changes committed.
- Forgetting the COMMIT or ROLLBACK. This gives ORA-06519.
- Expecting to read uncommitted caller data. The autonomous code sees only committed rows.
- Touching rows the caller has locked. This gives ORA-00060.
- Committing in a loop through a trigger. Row-level triggers with an autonomous commit scale badly.
- Nesting without limits. Each active autonomous transaction counts against the
TRANSACTIONSdatabase parameter. Deep or recursive nesting can exhaust it.
Exercises
Exercise
A procedure inserts a row into accounts, calls log_msg('inserted'), and then the caller issues ROLLBACK. Which rows exist afterwards: the account row, the audit_log row, or both?
Show answer
Only the auditlog row exists. The account insert belongs to the caller's transaction, which was rolled back. The `logmsg` insert ran in its own autonomous transaction and was committed before the rollback.
Exercise
A developer writes an autonomous procedure that updates accounts row 2 and commits. It is called from a block that has already updated row 2 but has not committed. What happens, and why?
Show answer
Oracle raises ORA-00060 (deadlock detected) in the autonomous transaction. The caller is suspended but still holds the lock on row 2, so the autonomous transaction waits for a lock that cannot be released until the autonomous transaction finishes. The fix is to keep autonomous code away from rows the caller modifies, or to restructure so that the update happens after the caller commits.
Exercise
What error do you get if an autonomous procedure inserts a row and returns without COMMIT or ROLLBACK, and what happens to the inserted row?
Show answer
ORA-06519, "active autonomous transaction detected and rolled back". The insert is rolled back, so the row is not saved.