Sub topic 15
Listing, Disabling, Enabling, and Debugging Triggers
This chapter assumes you can write the triggers from earlier chapters (BEFORE, AFTER, INSTEAD OF, compound) and that you know basic data dictionary queries and SQL*Plus or SQLcl. The examples use the employees table and the employees_aud trigger from the audit chapter.
Finding triggers in the data dictionary
Oracle stores trigger metadata in three view families. Each one has the same columns and differs only in scope.
| View | Shows | Notes |
|---|---|---|
| `USER_TRIGGERS` | Triggers you own | Fine for day-to-day work |
| `ALL_TRIGGERS` | Triggers you can see | Includes other schemas' triggers on tables you can access |
| `DBA_TRIGGERS` | Every trigger in the database | Requires a DBA-level privilege |
The most useful columns are these:
TRIGGER_NAMETRIGGER_TYPE, for exampleBEFORE EACH ROWorCOMPOUNDTRIGGERING_EVENT, for exampleINSERT OR UPDATETABLE_NAMEandBASE_OBJECT_TYPESTATUS, which isENABLEDorDISABLEDWHEN_CLAUSETRIGGER_BODY
TRIGGER_BODY is a LONG column, which is awkward to filter or join. To search trigger code, query USER_SOURCE instead.
SELECT trigger_name, trigger_type, triggering_event, status, when_clause
FROM user_triggers
WHERE table_name = 'EMPLOYEES'
ORDER BY trigger_name;
SELECT line, text
FROM user_source
WHERE name = 'EMPLOYEES_AUD'
AND type = 'TRIGGER'
ORDER BY line;Trigger names share a namespace with other schema objects such as tables and views. Two triggers in one schema cannot have the same name, even on different tables.
Enabled, disabled, and invalid
Do not confuse STATUS in USER_TRIGGERS with validity. STATUS records whether you switched the trigger on or off. Validity, shown as STATUS in USER_OBJECTS, records whether the code compiled and is current. A trigger can be enabled and invalid at the same time.
A new trigger is enabled unless the CREATE statement includes a DISABLE clause. That clause goes before the WHEN clause and the body.
Disabling and enabling
There are two levels of control.
-- One trigger
ALTER TRIGGER employees_aud DISABLE;
ALTER TRIGGER employees_aud ENABLE;
-- Every trigger on one table
ALTER TABLE employees DISABLE ALL TRIGGERS;
ALTER TABLE employees ENABLE ALL TRIGGERS;These commands have side effects you should plan for:
- The change is global. Every session stops firing the trigger, not only yours. Another user inserting while you load data skips the audit row, the sequence assignment, or the validation check.
- It is DDL. It commits the current transaction first. Do not use it in the middle of work you may still need to roll back.
- It needs a lock. If other sessions hold uncommitted changes on the table, the statement can fail with
ORA-00054: resource busy. - It needs privileges. You must own the trigger or hold the right
ALTERprivilege on it or its table. - It is not a bypass for constraints. Constraints still apply when triggers are off. Only the trigger logic is skipped.
Treat DISABLE ALL TRIGGERS as a maintenance tool. Always re-enable the triggers in the same script, and check afterward:
SELECT trigger_name, status
FROM user_triggers
WHERE table_name = 'EMPLOYEES'
AND status <> 'ENABLED';If this returns rows after a load, you forgot something.
If you need a bypass only for certain sessions, say a data migration job, do not disable the trigger. Put a check inside it, such as a package variable or an application context flag, so other sessions are unaffected.
Compilation errors
Oracle lets you create a trigger that does not compile. The statement ends with "Warning: Trigger created with compilation errors", and the trigger is stored as INVALID. This is where triggers differ most from ordinary code. An invalid enabled trigger blocks the DML it guards:
INSERT INTO employees (employee_id, last_name, department_id)
VALUES (999, 'Test', 10);
-- ORA-04098: trigger 'HR.EMPLOYEES_AUD' is invalid and failed re-validationA typing mistake in an audit trigger can therefore stop all inserts into the table until you fix it. Always check for errors after you deploy a trigger.
In SQL*Plus and SQLcl, SHOW ERRORS displays the errors from the last compile. You can also pass the object explicitly:
SHOW ERRORS TRIGGER employees_audOther clients, such as application code or some IDEs, do not support SHOW ERRORS. There you can query the dictionary:
SELECT line, position, text
FROM user_errors
WHERE name = 'EMPLOYEES_AUD'
AND type = 'TRIGGER'
ORDER BY sequence;To find every invalid trigger in a schema:
SELECT object_name, status, last_ddl_time
FROM user_objects
WHERE object_type = 'TRIGGER'
AND status = 'INVALID';Fix the source and rerun CREATE OR REPLACE TRIGGER, or recompile without changing the code:
ALTER TRIGGER employees_aud COMPILE;Recompiling without changes is useful when a trigger became invalid because an object it depends on changed, such as a column dropped from the audit table. Oracle usually revalidates the trigger automatically the next time it fires. Compiling it yourself during deployment shows any error at once, not on the first user's DML.
Line numbers in USER_ERRORS count from the first line of the CREATE statement. Oracle stores the trigger header and body, so line 1 is the line that starts with CREATE.
You can also turn on compiler warnings for the session before you create triggers:
ALTER SESSION SET PLSQL_WARNINGS = 'ENABLE:ALL';Warnings do not make a trigger invalid, but they flag problems such as unreachable code.
Debugging a trigger that compiles but misbehaves
Runtime problems are harder than compile errors because the trigger runs inside someone else's DML statement. These techniques help.
Read the error stack
When a trigger raises an unhandled exception, the DML statement fails and the stack names the trigger and line:
ORA-20001: Salary cannot be decreased
ORA-06512: at "HR.EMPLOYEES_SALARY_CHK", line 2
ORA-04088: error during execution of trigger 'HR.EMPLOYEES_SALARY_CHK'The ORA-06512 line tells you where to look in USER_SOURCE. ORA-04088 confirms the failure was inside a trigger. Inside an exception handler, DBMS_UTILITY.FORMAT_ERROR_BACKTRACE returns the same stack for logging.
Log from an autonomous transaction
DBMS_OUTPUT works only if the client displays it, and its text vanishes if the statement fails far from your terminal. A logging table is more reliable. Because a failed statement rolls back everything, including your log rows, the logger must commit independently.
CREATE TABLE trigger_log (
logged_at TIMESTAMP DEFAULT SYSTIMESTAMP,
source VARCHAR2(100),
message VARCHAR2(4000)
);
CREATE OR REPLACE PROCEDURE log_msg (p_source VARCHAR2, p_message VARCHAR2) IS
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
INSERT INTO trigger_log (source, message) VALUES (p_source, p_message);
COMMIT;
END log_msg;
/Call it from the trigger with the values you want to inspect, for example log_msg('EMPLOYEES_AUD', 'old=' || :OLD.salary || ' new=' || :NEW.salary);. The autonomous commit affects only the log row, not the main transaction. Remove these calls when you finish, because every call adds a write and a commit to each row change.
Common causes of "my trigger does nothing"
Work through this checklist:
- Is the trigger
ENABLEDandVALID? - Does the event match? An
UPDATE OF salarytrigger ignores updates to other columns. - Does the
WHENclause exclude the row? It cannot be used on statement-level triggers, and it can refer toNEWandOLDonly without a colon. - Is the trigger a row-level trigger, so that it runs zero times when a statement changes zero rows?
- Did another trigger on the same table change the values first? Check the order with
FOLLOWS. - For
INSTEAD OFtriggers, are you writing to the view and not the base table?
Exercise
A deployment script ends with "Warning: Trigger created with compilation errors". Developers then report that every INSERT into the table fails with ORA-04098. Why does this happen, and what query shows the cause?
Show answer
The trigger was stored as INVALID but is still enabled, so Oracle tries to revalidate it on each INSERT, fails, and raises ORA-04098. Query USERERRORS filtered on NAME = the trigger name and TYPE = 'TRIGGER' (or run SHOW ERRORS TRIGGER triggername in SQL*Plus or SQLcl) to see the line, position and text. Then fix the source and recreate it, or run ALTER TRIGGER trigger_name COMPILE if a dependency was the problem.
Exercise
You run ALTER TABLE employees DISABLE ALL TRIGGERS, load 50,000 rows, and then ENABLE ALL TRIGGERS. Name two risks of this approach on a live system, and one alternative.
Show answer
Risks: the change is global, so other sessions' DML during the load skips auditing and validation. Also, the ALTER commits the current transaction and can fail with ORA-00054 if other sessions hold locks. Alternative: leave the triggers enabled and add a session-specific bypass flag (a package variable or application context) that the trigger checks before running its logic.