Sub topic 3
Firing Order and the FOLLOWS Clause
This section assumes you know basic PL/SQL blocks, COMMIT and ROLLBACK, and how a row trigger uses :NEW and :OLD.
Firing Order and the FOLLOWS Clause
When several triggers share the same timing point and event, Oracle fires them in an order you can set with FOLLOWS. Without it, the order is not guaranteed.
CREATE OR REPLACE TRIGGER employees_bi_second
BEFORE INSERT ON employees
FOR EACH ROW
FOLLOWS employees_bi
BEGIN
:NEW.last_name := UPPER(:NEW.last_name);
END employees_bi_second;
/Transactions Inside Triggers: No COMMIT and Autonomous Transactions
A trigger runs inside the transaction of the statement that fired it. It cannot issue COMMIT or ROLLBACK. To log work that must survive a rollback, declare PRAGMA AUTONOMOUS_TRANSACTION. The logging table employee_log is assumed to exist.
CREATE OR REPLACE TRIGGER employees_log_bi
BEFORE INSERT ON employees
FOR EACH ROW
DECLARE
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
INSERT INTO employee_log (employee_id, logged_at)
VALUES (:NEW.employee_id, SYSTIMESTAMP);
COMMIT;
END employees_log_bi;
/The Mutating Table Error (ORA-04091)
A row trigger cannot query or change the table that fired it while that table is still changing. Doing so raises ORA-04091. The fix is a compound trigger.
Compound Triggers as the Fix for Mutating Tables
A compound trigger groups the timing points into one object. Row sections collect values, and the AFTER STATEMENT section reads the table once the statement has finished.
DDL and Database Event Triggers
A schema-level trigger fires on DDL. The following trigger blocks dropping tables in the schema:
CREATE OR REPLACE TRIGGER no_drop_tables
BEFORE DROP ON SCHEMA
BEGIN
IF ORA_DICT_OBJ_TYPE = 'TABLE' THEN
RAISE_APPLICATION_ERROR(-20003, 'Dropping tables is not allowed in this schema');
END IF;
END no_drop_tables;
/Listing, Disabling, Enabling, and Debugging Triggers
Query USER_TRIGGERS to list triggers and their status. Use ALTER TRIGGER to enable or disable one trigger. Use SHOW ERRORS after a failed compile, or query USER_ERRORS.
SELECT trigger_name, trigger_type, triggering_event, status
FROM user_triggers
WHERE table_name = 'EMPLOYEES';
ALTER TRIGGER employees_bi_second DISABLE;
SHOW ERRORS TRIGGER employees_bi_secondBest Practices and Common Pitfalls
Keep trigger bodies short and move business logic into procedures. Avoid hidden writes that surprise other developers. Test order-dependent triggers with FOLLOWS and document the order.
Exercise
Trigger B must run after trigger A on the same table and event. Which clause do you add to B?
Show answer
Add FOLLOWS A to the header of trigger B, before its BEGIN.