Sub topic 16
Best Practices and Common Pitfalls
This chapter assumes you have read the earlier chapters. You should know the trigger types, :OLD and :NEW, the mutating table error, compound triggers and the transaction rules. Here we pull them into working rules and look at the mistakes that cause most trigger problems in production.
Decide Whether You Need a Trigger
A trigger runs implicitly, so a developer reading application code cannot see it. Use one only when nothing simpler enforces the rule.
Try these first:
- A
NOT NULL,CHECK, unique or foreign key constraint, when it can express the rule. - A column
DEFAULT, or an identity column (GENERATED BY DEFAULT ON NULL AS IDENTITY), instead of a sequence trigger likeemployees_bi. - A stored procedure that application code calls explicitly.
Triggers are a good fit when the rule must hold for every code path, including ad hoc SQL and other applications. Audit trails, derived columns and INSTEAD OF view handling are typical cases.
Keep Trigger Bodies Thin
A long trigger body is hard to test, and it is recompiled each time you replace it. Put the logic in a package and let the trigger pass in the values. The package can be unit-tested on its own, and several triggers can share it.
CREATE OR REPLACE PACKAGE emp_rules AS
PROCEDURE check_salary_change (p_old IN NUMBER, p_new IN NUMBER);
END emp_rules;
/
CREATE OR REPLACE PACKAGE BODY emp_rules AS
PROCEDURE check_salary_change (p_old IN NUMBER, p_new IN NUMBER) IS
BEGIN
IF p_new < p_old THEN
RAISE_APPLICATION_ERROR(-20001, 'Salary cannot be decreased');
END IF;
END check_salary_change;
END emp_rules;
/
CREATE OR REPLACE TRIGGER employees_salary_chk
BEFORE UPDATE OF salary ON employees
FOR EACH ROW
WHEN (NEW.salary <> OLD.salary)
BEGIN
emp_rules.check_salary_change(:OLD.salary, :NEW.salary);
END employees_salary_chk;
/The UPDATE OF and WHEN clauses do the filtering, so the PL/SQL engine is not entered for rows that do not qualify. On a bulk update, that saves work for every skipped row.
Pitfalls With Transactions
COMMIT and ROLLBACK in a trigger
A trigger runs inside the transaction of the statement that fired it. A COMMIT or ROLLBACK in the body raises ORA-04092. The same restriction applies to DDL statements, because they commit implicitly. If a trigger's work must survive a rollback, such as a log of rejected attempts, use an autonomous transaction.
CREATE TABLE trigger_log (
logged_at TIMESTAMP DEFAULT SYSTIMESTAMP NOT NULL,
message VARCHAR2(400)
);
CREATE OR REPLACE PROCEDURE log_event (p_message IN VARCHAR2) IS
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
INSERT INTO trigger_log (message) VALUES (p_message);
COMMIT;
END log_event;
/A trigger can call log_event just before it raises an error. The log row stays even though the main statement is rolled back.
Side effects that cannot be rolled back
Oracle can roll back a statement and restart it to keep reads consistent, for example when another session changes a row it was about to update. A row trigger can therefore fire more than once for the same logical change. Database changes are undone with the rollback. Sending email, calling UTL_HTTP, writing with UTL_FILE or incrementing a package variable is not undone, so the action can happen twice, or happen for a transaction that later rolls back.
Do not do external work directly in a trigger. Insert a row into a queue table, or enqueue a message. A job that runs after the commit then performs the action.
Errors abort the whole statement
An unhandled exception in a trigger fails the triggering statement, and Oracle rolls back that statement's changes. A statement that updates 10,000 rows is undone completely if the trigger fails on row 9,999. The error is wrapped in ORA-04088, with your original error below it in the stack. This is the behaviour you want from validation triggers. It is a risk for a non-essential trigger, such as a statistics collector, so keep that kind trivial and defensive.
Pitfalls With Table Access and Cascades
The mutating table error comes up when a row trigger reads or changes the table that fired it. Move the logic to a compound trigger, collecting keys in the row sections and querying in AFTER STATEMENT. Constraint checks are the one exception. Oracle also protects against a related case: a row trigger cannot change key columns of tables that are involved in a constraint with the triggering table.
Triggers can fire other triggers. Trigger A updates table B, which fires trigger B, which updates table A. Without a guard this recurses until Oracle stops it at the limit of 32 cascading trigger levels (ORA-00036 is the usual symptom). Even below that limit, cascades are hard to follow. When you design several triggers over related tables, draw out which trigger writes to which table before you code them.
Pitfalls in the Body of the Trigger
- Modifying
:NEWin an AFTER trigger. This fails at compile time. Assignments to:NEWbelong in BEFORE row triggers. - Using the colon in a
WHENclause. WriteWHEN (NEW.salary < OLD.salary). The colon form is only for the PL/SQL body. - Treating
NULLas a value.NEW.salary <> OLD.salaryevaluates to unknown when either side isNULL, so the trigger does not fire when salary changes fromNULLto a number. UseWHEN (NEW.salary IS DISTINCT FROM OLD.salary)on versions that support it, or addORconditions withIS NULL. - Relying on firing order without saying so. Triggers with the same timing point have no guaranteed order unless one uses
FOLLOWS. If two triggers depend on each other's results, state the order. - Large row-level work. A row trigger runs once per row. A query inside it on a 1,000,000-row update runs 1,000,000 times. Prefer set-based work in a compound trigger's
AFTER STATEMENTsection.
Deployment and Maintenance Pitfalls
Triggers can also fail for reasons that have nothing to do with their logic.
| Problem | Symptom | What to do |
|---|---|---|
| Trigger left disabled after a data load | Rows missing from audit tables, rules not enforced | Query `USER_TRIGGERS` for `DISABLED` triggers after loads, and make the enable step part of the load script |
| Trigger with compile errors | `ORA-04098: trigger is invalid and failed re-validation` on every DML statement | Run `SHOW ERRORS TRIGGER name`, fix it, and recompile with `ALTER TRIGGER name COMPILE` |
| Dependency changed | A trigger becomes `INVALID` after a table or package is altered | Check `USER_OBJECTS` after each deployment |
| Broken logon trigger | Users cannot connect | Handle exceptions in the body, and keep a session open with `ADMINISTER DATABASE TRIGGER` while you test |
| `DISABLE ALL TRIGGERS` on a shared table | Other sessions' DML skips the rules during your load | Disable only the trigger you need, and only in a maintenance window |
This query checks for both problems after a deployment:
SELECT trigger_name, table_name, status
FROM user_triggers
WHERE status = 'DISABLED';
SELECT object_name, status
FROM user_objects
WHERE object_type = 'TRIGGER'
AND status = 'INVALID';A failing system trigger can be more serious than a failing table trigger. If a BEFORE DROP ON SCHEMA or AFTER LOGON ON DATABASE trigger raises an unexpected error, normal users are blocked from the action it guards. For logon triggers, wrap the body in an exception handler that records the problem and lets the user in, unless denying access is the purpose of the trigger.
A Checklist for Reviewing a Trigger
- Could a constraint, default, identity column or procedure do the job instead?
- Does it use the narrowest event:
UPDATE OFthe specific columns, plus aWHENclause? - Is the body short, with the logic in a package that has its own tests?
- Does it avoid
COMMIT,ROLLBACK, DDL and external calls? - Does it avoid querying or changing its own table in a row trigger?
- Is the order relative to other triggers on the same event explicit, using
FOLLOWSwhere it matters? - Does the deployment script check
USER_TRIGGERSandUSER_OBJECTSfor disabled or invalid triggers?
Exercise
A BEFORE UPDATE row trigger on orders sends a confirmation email by calling UTL_SMTP. In testing, some customers receive two emails for a single order change, and others receive an email for a change that was later rolled back. Explain why this happens and what design avoids it.
Show answer
Oracle can roll back and restart a statement to keep reads consistent, so a row trigger can fire more than once for one logical change. The email call is not part of the transaction, so a rollback cannot undo it. A later ROLLBACK also leaves the email already sent. The fix is to have the trigger only insert a row into a notification queue table, which is rolled back with the transaction. A scheduled job or queue consumer sends the email after the commit and marks the row as sent.
Exercise
You need to record every rejected salary decrease in trigger_log, even though the update itself is rolled back. Which mechanism do you use, and what must you avoid doing with it?
Show answer
Call a procedure declared with PRAGMA AUTONOMOUS_TRANSACTION, such as log_event, from the trigger just before RAISE_APPLICATION_ERROR. The log insert is committed in its own transaction, so it survives the rollback of the main statement. Avoid using the autonomous transaction to read or change rows that the main transaction has modified. It cannot see uncommitted changes, and it can deadlock against the calling session if it touches locked rows.