A mutation error (ORA-04091: table is mutating, trigger/function may not see it) occurs when a row-level trigger tries to read, modify, or query the same table that is currently being modified by the trigger itself.
Why Does Mutation Error Occur?
Oracle prevents a trigger from reading or modifying a table while it is being updated to avoid inconsistent data (also known as a “mutating table”). This happens because:
1. The DML statement is modifying the table.
2. The row-level trigger fires for each row.
3. If the trigger tries to query the same table, Oracle detects an inconsistent state (since the table is still being modified) and raises a mutation error.
Example of Mutation Error
1. Creating a Table
CREATE TABLE employees (
emp_id NUMBER PRIMARY KEY,
name VARCHAR2(50),
salary NUMBER
);
2. Creating a Row-Level Trigger That Causes Mutation Error
3. Updating the Table (Causes Error)
How to Fix Mutation Errors?
1. Use a Compound Trigger (Oracle 11g and Later)
A compound trigger allows you to store temporary values in a global variable and process them in the AFTER STATEMENT section instead of row-level execution.
This avoids the mutation error because the AFTER STATEMENT section runs only once after all rows are modified, rather than during each row update.
2. Use an Autonomous Transaction for Logging (Not for Data Modification)
If you only need to log data, you can use an autonomous transaction so that the trigger runs in a separate transaction.
This avoids mutation errors only if the trigger is used for logging. It does not work if the trigger modifies the same table.
3. Use a Statement-Level Trigger Instead of a Row-Level Trigger
If you do not need to process each row individually, you can use a statement-level trigger that fires once for the entire operation.
No comments:
Post a Comment