Sub topic 12
Autonomous Transactions for Logging and Auditing
Assume you know basic SQL, can run a PL/SQL block, and understand COMMIT and ROLLBACK. An autonomous transaction is a separate transaction started by a PL/SQL routine, such as a procedure, function, trigger, or anonymous block. It can commit or roll back without committing or rolling back the transaction that called it.
This behavior is useful for audit records. An audit entry can survive even when the business operation fails.
How an autonomous transaction works
When the main transaction calls an autonomous routine:
- Oracle suspends the main transaction.
- The autonomous routine starts or continues its own transaction.
- The routine must end its transaction with
COMMITorROLLBACK. - Oracle resumes the main transaction.
The two transactions have separate commit points and separate locks.
Declare the routine with PRAGMA AUTONOMOUS_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;
EXCEPTION
WHEN OTHERS THEN
ROLLBACK;
RAISE;
END log_msg;
/The COMMIT belongs to the autonomous transaction. It does not commit changes made by the caller.
BEGIN
UPDATE accounts
SET balance = balance - 100
WHERE id = 1;
log_msg('Debited account 1');
ROLLBACK;
END;
/
SELECT msg
FROM audit_log
WHERE msg = 'Debited account 1';The account update is undone, but the audit row remains because log_msg committed independently.
Rules and failure modes
An autonomous routine must finish its own transaction. If it exits with uncommitted work, Oracle raises an error such as ORA-06519: active autonomous transaction detected and rolls back that autonomous work.
The autonomous routine cannot safely modify a row that the main transaction has already locked. The main transaction is suspended while the routine runs, so the routine may wait for a lock held by its caller. This can lead to a deadlock. Keep autonomous logging focused on separate audit tables and avoid reading or changing data that the main transaction is currently modifying.
Autonomous logging also does not make an audit record permanent if the database or instance fails before the logger commits. It provides an independent transaction boundary, not a guarantee against every failure.
Exercise
The caller updates an account and then calls an autonomous logger. The caller rolls back. Which changes remain?
Show answer
The account update is undone. The logger's row remains if the autonomous routine committed it successfully.