Sub topic 8
Building an Audit Trail
An audit trail is a table that records who changed which rows, when, and what the values were before and after. This chapter builds one with a single AFTER row trigger. It assumes you can already write a row trigger, read :OLD and :NEW, and use the INSERTING, UPDATING, and DELETING predicates from the earlier chapters.
Why a trigger suits auditing
Application code can write audit rows, but every code path that touches the table has to remember to do it. A trigger runs for every INSERT, UPDATE, and DELETE, whether the statement comes from your application, a script, or a DBA in SQL*Plus. The audit logic lives in one place and cannot be skipped by a caller.
An AFTER row trigger is the usual choice. By the time it fires, the row change has passed the table's constraints, so you do not log changes that were going to fail anyway. A BEFORE trigger could log a change that a later constraint check then rejects.
The audit table
The table stores one row per changed employee row. Both salary columns are nullable, because an insert has no old value and a delete has no new value.
CREATE TABLE employee_audit (
audit_id NUMBER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
employee_id NUMBER NOT NULL,
action VARCHAR2(6) NOT NULL,
old_salary NUMBER,
new_salary NUMBER,
changed_by VARCHAR2(128) NOT NULL,
changed_at TIMESTAMP NOT NULL
);The table has no foreign key to employees. If it had one, you could not keep audit rows for an employee who has been deleted, and recording deletions is one of the main reasons to audit.
The audit trigger
This trigger handles three events at once.
CREATE OR REPLACE TRIGGER employees_aud
AFTER INSERT OR UPDATE OF salary OR DELETE ON employees
FOR EACH ROW
DECLARE
l_action VARCHAR2(6);
BEGIN
IF INSERTING THEN
l_action := 'INSERT';
ELSIF UPDATING THEN
l_action := 'UPDATE';
ELSE
l_action := 'DELETE';
END IF;
INSERT INTO employee_audit
(employee_id, action, old_salary, new_salary, changed_by, changed_at)
VALUES
(COALESCE(:NEW.employee_id, :OLD.employee_id),
l_action,
:OLD.salary,
:NEW.salary,
SYS_CONTEXT('USERENV', 'SESSION_USER'),
SYSTIMESTAMP);
END employees_aud;
/Four details make this work:
- Event list.
UPDATE OF salarymeans updates that do not namesalaryin theSETclause do not fire the trigger. Inserts and deletes fire it regardless of columns. - Action label. The
INSERTINGandUPDATINGpredicates setl_action. Anything else must be a delete, so the finalELSEcovers it. - Row id.
:NEWis empty on a delete and:OLDis empty on an insert.COALESCEpicks whichever one has a value. - Who and when.
SYS_CONTEXT('USERENV', 'SESSION_USER')returns the database user of the session.SYSTIMESTAMPrecords the time, including fractional seconds and time zone.
What the trigger records
The following script assumes your employees table has the columns employee_id, last_name, department_id, and salary, and that no other column is NOT NULL. Adjust the insert if your table differs.
INSERT INTO employees (employee_id, last_name, department_id, salary)
VALUES (9001, 'Lovelace', 10, 5000);
UPDATE employees SET salary = 5500 WHERE employee_id = 9001;
DELETE FROM employees WHERE employee_id = 9001;
SELECT employee_id, action, old_salary, new_salary
FROM employee_audit
WHERE employee_id = 9001
ORDER BY audit_id;The query returns three rows:
| employee_id | action | old_salary | new_salary |
|---|---|---|---|
| 9001 | INSERT | (null) | 5000 |
| 9001 | UPDATE | 5000 | 5500 |
| 9001 | DELETE | 5500 | (null) |
If you also have the salary-decrease trigger from the earlier chapter, the update here raises a salary increase only, so it passes.
How the audit row shares the transaction
The audit insert runs inside the same transaction as the change that fired the trigger. The diagram shows what that means.
This is usually what you want. The audit trail matches the committed data exactly. A rolled-back change leaves no audit row, because it never happened as far as the database is concerned.
The trigger must not issue COMMIT or ROLLBACK itself. Oracle raises an error if a trigger tries. If you need to record attempts that are later rolled back, such as rejected salary decreases, the audit insert must run in an autonomous transaction. That technique is covered in the chapter on transaction rules in triggers.
Auditing only real changes
UPDATE OF salary fires when salary appears in the SET clause, even if the new value equals the old one. UPDATE employees SET salary = salary therefore writes an audit row for every row it touches, with identical old and new values.
You can filter these with a WHEN clause. A plain comparison such as WHEN (NEW.salary <> OLD.salary) has a null problem: if either side is null, the comparison is unknown and the trigger does not fire. Because the clause applies to every event in the trigger, this would also suppress the insert and delete rows, where one side is always null. A null-safe test such as DECODE(NEW.salary, OLD.salary, 0, 1) = 1 treats two nulls as equal and a null against a value as different, so inserts and deletes still fire. Alternatively, keep the WHEN clause off and test inside the body with IF UPDATING AND ... THEN.
Choosing what to capture
A narrow audit table like this one only tracks salary. To audit more, you have three options:
- Add one old/new column pair per audited column. This is easy to query but needs a schema change for every new column.
- Write one row per changed column. Use columns such as
column_name,old_value, andnew_value. This scales to any column but needs more rows and anIFper column in the trigger. - Store the whole row. A
SELECT *-style copy of:OLDand:NEWis simple but uses the most space.
Pick based on how you will query the trail. "Who changed this salary?" is easy with option 1 or 2. "What did this row look like on a given date?" is easier with option 3.
Limits and pitfalls
- The session user may not be the real user. With a connection pool, every session is the same database account. Set
DBMS_SESSION.SET_IDENTIFIERfrom the application and readSYS_CONTEXT('USERENV', 'CLIENT_IDENTIFIER')in the trigger as well. - A disabled trigger leaves a gap.
ALTER TABLE employees DISABLE ALL TRIGGERSstops all auditing without any record of it. Limit who holds the privilege to do this, and checkuser_triggers.statusas part of routine monitoring. - Protect the audit table. The schema that owns
employeescan usually also update or delete audit rows. Keep the audit table in a separate schema, or grant application usersSELECTonly. - Every audited change costs an extra insert. On tables with heavy batch updates, the trigger adds a row-by-row insert for each changed row. Measure before putting it on a hot table.
- Do not query
employeesfrom the row trigger. Reading the table that fired a row trigger can raise ORA-04091, the mutating table error, covered in a later chapter. Everything this trigger needs comes from:OLD,:NEW, andSYS_CONTEXT, so it is safe.
Exercise
The audit trigger above uses AFTER UPDATE OF salary. A developer runs UPDATE employees SET last_name = 'Smith' WHERE employee_id = 100;. Is an audit row written? What happens if the developer runs UPDATE employees SET salary = salary WHERE employee_id = 100;?
Show answer
No audit row is written for the first statement, because salary is not in the SET clause and UPDATE OF salary restricts the trigger to updates that name that column. The second statement does write a row, because salary is named in the SET clause. The old and new salary in that row are equal.
Exercise
A session runs an update on employees that fires employees_aud, and then issues ROLLBACK. What does employee_audit contain for that change, and why?
Show answer
Nothing. The audit insert runs in the same transaction as the update, so the rollback undoes both. To keep a record of rolled-back attempts, the audit insert would need to run in an autonomous transaction.