PL/SQL Triggers — 47-Trigger Cascade Downed Batch
A 47-trigger cascade from one UPDATE caused 2.35M invocations and a 30-minute timeout on 50,000 orders.
20+ years shipping high-throughput database systems. Everything here is grounded in real deployments.
- ✓Solid grasp of fundamentals
- ✓Comfortable reading code examples
- ✓Basic production concepts
- A PL/SQL trigger is an automatic PL/SQL block that fires on DML, DDL, or system events
- Row-level triggers fire once per affected row; statement-level triggers fire once per statement
- :NEW and :OLD pseudorecords give access to row data before and after the change
- Mutating table error (ORA-04091) occurs when a row-level trigger queries its own table — fix with compound triggers
- DDL triggers audit schema changes; system event triggers (LOGON, SERVERERROR) are invaluable for production observability
- Use CALL syntax (12c+) to keep trigger logic in testable procedures, not inline
A PL/SQL trigger is an automatic action that Oracle fires when something happens to a table — like a guard that watches the door and reacts immediately whenever someone enters or leaves, without you having to call them manually.
A PL/SQL trigger is a stored program that Oracle executes automatically in response to a database event — an INSERT, UPDATE, or DELETE on a table or view, a DDL statement, or a system event like logon or shutdown. Unlike stored procedures, triggers are not called explicitly; they fire in reaction to events. This makes them powerful for enforcing business rules, maintaining audit trails, and synchronising derived data — and dangerous when overused.
I have debugged production systems where a single UPDATE cascaded through 8 triggers across 6 tables, executing 47 trigger bodies before completing. I have seen DDL triggers lock a DBA out of their own schema. I have seen a team lose 3 months of audit data because their audit trigger did not use an autonomous transaction, and a batch rollback wiped the audit log clean. Triggers are a sharp tool — this guide covers everything from the basics to the patterns that prevent these disasters.
What is a PL/SQL Trigger?
A trigger is a named database object containing a PL/SQL block that Oracle executes automatically whenever a specified DML event occurs on a table or view. The trigger fires without any explicit call from the application — you define the condition once, and Oracle enforces it for every matching operation, regardless of which application or user performs the DML.
Triggers are used primarily for: enforcing complex business rules that CHECK constraints cannot express (constraints cannot reference other tables or use session context), maintaining audit tables that record who changed what and when, automatically populating derived columns (e.g., last_modified_by, last_modified_date), and replicating changes to denormalised summary tables.
Triggers execute within the triggering transaction. If the trigger raises an exception, the triggering DML statement is rolled back. If you call COMMIT or ROLLBACK inside a trigger, Oracle raises ORA-04092.
A common misconception is that triggers are always faster than application code. In reality, a trigger adds the overhead of a PL/SQL context switch for every row. For bulk operations, that overhead adds up fast. Always benchmark with realistic data volumes before relying on a trigger for performance-sensitive logic.
Trigger Types — BEFORE vs AFTER, Row vs Statement Level
Oracle triggers have two orthogonal dimensions: when they fire (BEFORE or AFTER the DML) and how many times they fire (once per row or once per statement).
BEFORE triggers fire before the DML operation executes. For row-level BEFORE triggers, you can modify the :NEW pseudorecord to change the value being inserted or updated before it hits the table. This is the correct place for defaulting values, reformatting data, and enforcing rules that need to change the incoming data.
AFTER triggers fire after the DML succeeds. You cannot modify :NEW in AFTER triggers. AFTER is the correct choice for auditing (the row is committed, so you know the operation succeeded) and for updating other tables based on the completed change.
Row-level triggers (FOR EACH ROW) fire once per affected row. Statement-level triggers (no FOR EACH ROW) fire once per DML statement regardless of how many rows are affected — even zero rows. For auditing individual row changes, use row-level. For logging that a statement was executed, use statement-level.
A word on combinations: You can have multiple triggers on the same event. For example, a BEFORE row-level trigger for defaulting values and an AFTER row-level trigger for auditing. In Oracle 11g+, you control execution order with FOLLOWS and PRECEDES. Without them, order is alphabetical by trigger name — fragile and silent.
:NEW and :OLD Pseudorecords — Reading Row Data Inside a Trigger
:NEW and :OLD are correlation names that provide access to the row being affected by the DML statement. They are available only in row-level triggers (FOR EACH ROW).
:OLD holds the values of the row before the DML operation. For INSERT, :OLD is NULL for all columns (there was no existing row). For DELETE, :NEW is NULL (the row is being removed). For UPDATE
The Mutating Table Error (ORA-04091)
ORA-04091 is the most notorious trigger error. It occurs when a row-level trigger tries to query or modify the table that fired the trigger. Oracle raises this error to prevent inconsistent reads during a DML operation that has not yet completed.
Example: an AFTER UPDATE row-level trigger on employees queries SELECT COUNT(*) FROM employees. Oracle cannot allow this — the DML is mid-flight and the table is in an inconsistent state.
Three solutions: 1. Compound triggers (Oracle 11g+): a single trigger with multiple firing points. Collect the IDs in an AFTER EACH ROW section into a package-level collection, then query the table in the AFTER STATEMENT section when the DML is complete. 2. Autonomous transactions: not recommended for this pattern — it processes data in a separate transaction that cannot see uncommitted changes from the triggering transaction. 3. Rethink the design: if a trigger queries the same table, the logic may belong in a stored procedure called from the application, where you have full control over the transaction.
Performance note: Compound triggers collect data in PGA memory. For DML affecting millions of rows, this can cause excessive PGA consumption. Always test with realistic row counts to ensure you don't swap from ORA-04091 to ORA-04030 (out of PGA memory).
INSTEAD OF Triggers — Enabling DML on Views
By default, you cannot perform DML (INSERT, UPDATE, DELETE) on a view that involves joins, aggregate functions, DISTINCT, GROUP BY, or set operators. Oracle raises ORA-01779. INSTEAD OF triggers solve this.
An INSTEAD OF trigger fires in place of the DML operation on the view. Oracle intercepts the INSERT/UPDATE/DELETE and executes your trigger code instead of attempting to modify the view directly. Your trigger code then updates the underlying base tables explicitly.
This is the standard pattern for updatable views in Oracle. It lets the application interact with a simplified, business-friendly view while the trigger handles the complexity of distributing the DML across the underlying tables.
A common mistake: creating INSTEAD OF triggers for only one DML type. If an application issues DELETE on a view and only an INSERT trigger exists, Oracle raises ORA-01779 again. Always create triggers for all DML operations that the application will use.
DDL Triggers — Auditing Schema Changes
DDL triggers fire in response to CREATE, ALTER, DROP, GRANT, REVOKE, or TRUNCATE statements on schema objects. They are the DBA tool for tracking who changed what in the database schema.
Three essential DDL trigger use cases: 1. Audit logging: Record every DDL change (who ran it, when, what SQL) into a schema_change_log table. When someone drops a table at 2am and nobody knows who did it, this log is your only evidence. 2. Enforce naming conventions: Reject table names without a prefix, reject columns named ID without a table prefix. 3. Prevent accidental drops: Block DROP TABLE, DROP INDEX, DROP SEQUENCE in production schemas.
The ORA-04045 trap: If your DDL trigger has a compilation error, Oracle cannot compile it. Since DDL triggers fire on CREATE/ALTER, you cannot create or alter ANY object in the schema until you fix the trigger. Always test DDL triggers in dev first.
Performance impact: DDL triggers add latency to every DDL command. If you have hundreds of developers running migrations, a slow DDL trigger can cause timeouts. Keep the body fast — avoid queries to remote tables or heavy validation.
System Event Triggers — LOGON, LOGOFF, and SERVERERROR
System event triggers fire on database-level events: LOGON, LOGOFF, SERVERERROR, and STARTUP/SHUTDOWN. They are the most underused but most valuable trigger category.
The SERVERERROR trigger is the one I deploy on every production schema. It fires after every Oracle error. When a batch job fails at 3am with a generic error, the SERVERERROR trigger captures the full error stack, the SQL that caused it, and all bind variables — without any application changes.
LOGON triggers enforce security policies: reject connections from untrusted IPs, enforce MFA validation, set session context. But they are dangerous: if your LOGON trigger has an error, nobody can log in to fix it. Always include an exception handler that allows DBA logins.
Resource usage: A SERVERERROR trigger fires on every single error, including harmless ones like ORA-00001 (unique constraint violation) that applications handle. This can flood your error log table. Use a filtering condition (e.g., ORA_SERVER_ERROR(1) IN (list of critical errors)) to reduce noise.
CALL Syntax — The Clean Way to Write Triggers
Oracle 12c introduced CALL syntax, which lets you invoke a stored procedure directly from the trigger definition instead of writing the PL/SQL block inline. This is a significant design improvement.
The old pattern: 200 lines of PL/SQL logic inside the trigger body. Hard to test independently, hard to version-control separately, impossible to call from other contexts.
The new pattern: One procedure per business rule, called from one trigger per event. The procedure is independently testable, version-controllable, and reusable. The trigger just wires the event to the procedure.
Why this matters: When you need to test the logic without firing the trigger, you call the procedure directly. When you need to run the same logic during a data migration, you call the procedure directly. When you need to unit test the business rule, you call the procedure directly.
Trade-off: CALL syntax adds a small overhead because Oracle resolves the procedure call dynamically. For row-level triggers on high-throughput tables, inline PL/SQL might be slightly faster. But the maintainability gain usually outweighs the micro-performance cost.
Cascading Triggers — The Hardest Production Bug to Diagnose
Cascading triggers occur when trigger A on table X modifies table Y, which fires trigger B on table Y, which modifies table Z, and so on. Oracle has a default limit of 50 trigger cascades before raising an error.
The danger: Infinite loops if trigger A modifies its own table through a stored procedure (bypassing the mutating table check). Silent performance degradation if each trigger adds 1ms and the chain fires 47 times.
The production nightmare: I inherited a system where 8 triggers cascaded across 6 tables. A single UPDATE on the root table triggered 47 trigger executions. The fix was consolidating the logic into 2 compound triggers and removing redundant cross-table triggers.
The design rule: Each trigger should do one thing. If trigger A needs to modify another table, that is fine — but document the dependency chain. If your chain exceeds 3 levels, refactor into stored procedures.
The debugging technique: Before deploying cascading triggers, map the dependency chain. Query USER_TRIGGERS for every table involved and trace which trigger modifies which table. Use USER_DEPENDENCIES to find what each trigger references.
Autonomous Transactions in Triggers — Logging That Survives Rollback
An autonomous transaction (PRAGMA AUTONOMOUS_TRANSACTION) creates a separate transaction within the trigger that can COMMIT independently of the triggering transaction.
The legitimate use case: Error logging. If you want error records to survive even when the triggering transaction rolls back, use an autonomous transaction for the error INSERT. SERVERERROR triggers and connection logging are the standard autonomous transaction use cases.
The danger: Autonomous transactions cannot see uncommitted changes from the triggering transaction. If you query the triggering table in the autonomous transaction, you see the committed state, not the mid-DML state.
The phantom record problem: If you use autonomous transactions for successful-operation audit triggers, you get phantom records — rows in the audit table whose triggering DML was rolled back. The audit trail says the operation happened, but the data says it did not.
Another risk: Autonomous transactions can cause deadlocks if they try to modify tables also being modified by the main transaction. Because they run in a separate session, two autonomous transactions on the same session can block each other.
TRUNCATE vs DELETE — The Audit Bypass You Did Not Know About
TRUNCATE is DDL, not DML. DML triggers do NOT fire on TRUNCATE. This is one of the most common trigger misconceptions, and it has real security implications.
DELETE: Fires DELETE triggers (row-level and statement-level). Logged in redo logs. Can be rolled back. TRUNCATE: Does NOT fire any DML triggers. Minimal redo logging. Cannot be rolled back (implicit COMMIT). Much faster than DELETE.
The security implication: If your audit trigger is designed to catch all deletions, TRUNCATE bypasses it completely. A DBA can TRUNCATE a table and no audit record is created.
The production story: A team had a trigger-based audit system that logged every DELETE. During a performance investigation, a DBA ran TRUNCATE TABLE orders to clear test data. The audit log showed nothing. The DBA thought the table was empty. It was not — it was production data. The TRUNCATE was fast, silent, and irreversible.
Defence: Use a DDL trigger to catch TRUNCATE events and either log them or block them entirely. For tables that require audit, consider using FLASHBACK TABLE instead of TRUNCATE for removal.
FOLLOWS and PRECEDES — Explicit Trigger Ordering
Oracle 11g+ introduced FOLLOWS and PRECEDES clauses to control trigger execution order when multiple triggers exist on the same event. Before this, execution order was alphabetical by trigger name — fragile and undocumented.
FOLLOWS: This trigger fires after the specified trigger. PRECEDES: This trigger fires before the specified trigger.
When to use: When you genuinely need multiple triggers on the same event and one depends on the other side effects. For example, trigger A defaults a value, trigger B validates it — B must FOLLOWS A.
When NOT to use: If you can consolidate the logic into a single trigger, do that instead. Multiple triggers on the same event are inherently harder to reason about. FOLLOWS makes the dependency explicit, but a single trigger eliminates the dependency entirely.
Another pitfall: If you specify FOLLOWS a trigger that does not exist, Oracle raises ORA-25005. Always verify the referenced trigger name exists and is on the same table and event combination.
Error Handling in Triggers — RAISE_APPLICATION_ERROR and the Rollback Effect
When a trigger raises an exception, the entire triggering DML is rolled back — not just the last row, but the entire statement. If you INSERT 1000 rows and row 500 triggers an exception, all 1000 inserts are rolled back.
The audit implication: If your trigger inserts an audit record before raising an exception, that audit INSERT is also rolled back (unless it uses an autonomous transaction). You lose the record of the failed attempt.
RAISE vs RAISE_APPLICATION_ERROR: RAISE re-raises the current exception (useful in EXCEPTION blocks). RAISE_APPLICATION_ERROR creates a custom error with your message. Use RAISE_APPLICATION_ERROR for business rule violations with meaningful messages.
ORA-04092: The error you get if you COMMIT or ROLLBACK inside a trigger. Triggers execute within the triggering transaction — you cannot control the transaction boundary.
Custom error codes: Use the range -20000 to -20999 for RAISE_APPLICATION_ERROR. Choose codes consistently per module (e.g., -20xxx for order triggers, -21xxx for inventory). This makes log analysis easier.
The 'Fires Exactly Once' Myth — Why Your Trigger Runs More Than You Think
Most devs assume a trigger runs once per statement. Row-level triggers run once per affected row. That sounds obvious until a batch update hits 10,000 rows and your 'quick audit log' becomes a 10,000-row insert that locks the table for 30 seconds.
The real trap is when you combine statement-level and row-level triggers on the same event. Say you have a BEFORE INSERT statement trigger to set a session variable and a BEFORE INSERT row trigger to validate data. The statement trigger fires once. The row trigger fires N times. If your statement trigger logic depends on row-level state, you just signed up for a heisenbug.
Worse: compound triggers in Oracle 11g+ let you bundle both levels into one object. That's powerful, but it also means you can accidentally run the same logic twice — once at statement level, once at row level — if you don't gate your sections with conditional checks.
Audit your trigger count per table. If you see more than two triggers per DML operation, you've got a design problem. Combine them or rethink the logic.
Conditional Predicates — The Most Overlooked Performance Killers
You wrote a trigger on UPDATE to check IF :NEW.salary != :OLD.salary, so it only fires when salary changes. Congrats, you just avoided unnecessary row locks. But what about the developer who later adds a column to the same table and forgets to audit the trigger?
Here's the kicker: triggers fire on ALL columns unless you specify a column list in the trigger definition. That means your UPDATE trigger runs even when someone updates the middle_name column, which has nothing to do with salary validation. The trigger checks the condition anyway, burning CPU on every row.
Use the UPDATE OF clause to scope triggers to specific columns. It's not just a performance win — it prevents logic bugs when the schema evolves. Also, the UPDATING('column_name') function inside the trigger body lets you write per-column logic without convoluted IF chains.
Another old-school trick: check IF UPDATING THEN ... END IF to separate INSERT and UPDATE paths. But if you find yourself nesting more than two conditions, refactor that trigger into separate triggers — one per operation. Readability is a feature.
In production, I once saw a trigger check UPDATING on 12 columns with nested IFs. It was 400 lines and nobody knew what it actually did. We replaced it with 5 small triggers and deleted half the code. Audit your triggers like you audit your API endpoints.
9.6 Subprograms Invoked by Triggers
A trigger body can invoke stored procedures, functions, or packages, but the calling rules differ from standalone execution. Every called subprogram inherits the triggering session's transaction context — including the parent DML that fired the trigger. If that parent transaction later rolls back, any changes made by the called subprogram roll back too, even if the subprogram issued its own COMMIT. This hidden coupling is why production teams report phantom data: a trigger calls a logging procedure that inserts into an audit table, the main DML fails, and both disappear. The fix is to audit with autonomous transactions or pass the context explicitly via parameters. Additionally, functions called from triggers must be deterministic or invoked in a SELECT INTO, not a standalone expression, to avoid mutating-table errors. Always check that called subprograms do not perform DDL, execute dynamic SQL altering the trigger's own table, or raise unhandled exceptions that bubble into the trigger and abort the parent operation. The contract is strict: the subprogram must be safe, idempotent, and autonomous only when isolation is required.
Conclusion
PL/SQL triggers remain a double-edged sword in database systems. When used with precision, they enforce business rules, maintain audit trails, and protect data integrity without application overhead. Yet every trigger you write carries hidden risks: ordering surprises from concurrent execution, bypassable audit gaps from TRUNCATE, transactional coupling that swallows logs, and the persistent myth that a statement-level trigger fires exactly once per statement — in reality it fires once per triggering event stream, which can include multiple rows in batch operations. This series walked from DDL auditing to autonomous transaction patterns, explicit FOLLOWS/PRECEDES ordering, conditional predicate tuning, and safe subprogram invocation. The key takeaway is not to avoid triggers but to audit them with the same rigor you apply to stored procedures. Document every trigger's firing order, test with concurrent sessions, verify rollback behavior, and always ask: 'Does this logic belong in the database, or is it better served by application code?' When the answer is database, structure your trigger as a thin call to a packaged subprogram — testable, versionable, and cacheable. That discipline turns triggers from a debugging nightmare into a predictable enforcement layer.
The 47-Trigger Cascade That Brought Down a Payment Batch
- Map every trigger dependency chain before deploying to production. Keep chains shallow (max 3 levels).
- Use compound triggers to consolidate multiple operations on the same table into a single trigger body.
- Document every cross-table trigger modification. Include the table being modified and the affected triggers.
- Add a trigger execution counter (via autonomous transaction log) during regression testing to detect unexpected cascades.
SELECT trigger_name, trigger_type, triggering_event, status FROM user_triggers WHERE table_name = '<TABLE_NAME>';ALTER TABLE <TABLE_NAME> DISABLE ALL TRIGGERS; -- re-run DML to isolate| File | Command / Code | Purpose |
|---|---|---|
| plsql_triggers_example.sql | CREATE OR REPLACE TRIGGER trigger_name | What is a PL/SQL Trigger? |
| plsql_triggers_example.sql | CREATE OR REPLACE TRIGGER trg_employees_bi | Trigger Types |
| plsql_triggers_example.sql | CREATE OR REPLACE TRIGGER trg_salary_check | :NEW and :OLD Pseudorecords |
| plsql_triggers_example.sql | CREATE OR REPLACE TRIGGER trg_check_dept_budget | The Mutating Table Error (ORA-04091) |
| plsql_triggers_example.sql | CREATE OR REPLACE VIEW v_emp_dept AS | INSTEAD OF Triggers |
| plsql_ddl_triggers.sql | CREATE TABLE schema_change_log ( | DDL Triggers |
| plsql_system_event_triggers.sql | CREATE OR REPLACE TRIGGER trg_capture_errors | System Event Triggers |
| plsql_call_syntax.sql | CREATE OR REPLACE PACKAGE io_thecodeforge_order_triggers AS | CALL Syntax |
| plsql_cascading_triggers.sql | CREATE OR REPLACE TRIGGER trg_orders_ai | Cascading Triggers |
| plsql_autonomous_triggers.sql | CREATE OR REPLACE TRIGGER trg_server_error | Autonomous Transactions in Triggers |
| plsql_truncate_vs_delete.sql | CREATE OR REPLACE TRIGGER trg_test_delete | TRUNCATE vs DELETE |
| plsql_trigger_follows.sql | CREATE OR REPLACE TRIGGER trg_orders_defaults | FOLLOWS and PRECEDES |
| plsql_trigger_errors.sql | CREATE OR REPLACE TRIGGER trg_validate_salary | Error Handling in Triggers |
| TriggerMultipleFires.sql | CREATE OR REPLACE TRIGGER trg_orders_before_insert_stmt | The 'Fires Exactly Once' Myth |
| ConditionalTriggerEfficiency.sql | CREATE OR REPLACE TRIGGER trg_emp_salary_audit_bad | Conditional Predicates |
| TriggerCallSubprogram.sql | CREATE OR REPLACE PROCEDURE log_order_change( | 9.6 Subprograms Invoked by Triggers |
| TriggerBestPractice.sql | CREATE OR REPLACE PACKAGE pkg_emp_audit AS | Conclusion |
Key takeaways
Interview Questions on This Topic
What is the difference between a row-level and a statement-level trigger? When would you use each?
Frequently Asked Questions
20+ years shipping high-throughput database systems. Everything here is grounded in real deployments.
That's PL/SQL. Mark it forged?
12 min read · try the examples if you haven't