🧩 How to Fix ORA-04091: Table is Mutating, Trigger/Row Change
🧩 Introduction:
The ORA-04091 error occurs when a trigger tries to query or modify the table that is currently being modified by the same statement. This is known as a mutating table error and is common when using row-level triggers. Proper understanding and techniques are needed to avoid disrupting transactions and ensure data integrity.
Step 1: Identify the Trigger Causing the Error
Check which trigger is firing during the operation:
SELECT trigger_name, table_name, status
FROM user_triggers
WHERE table_name = 'MY_TABLE';
➡️ Replace MY_TABLE with the affected table.
Step 2: Understand Trigger Type
Mutating errors usually occur in row-level triggers (FOR EACH ROW). Consider if you are querying or updating the same table inside this trigger.
Step 3: Use Compound Trigger (Recommended)
In Oracle 11g and later, you can replace row-level triggers with compound triggers, which separate timing points for BEFORE STATEMENT, AFTER EACH ROW, and AFTER STATEMENT. This prevents mutating errors.
Example:
CREATE OR REPLACE TRIGGER my_table_compound_trg
FOR INSERT OR UPDATE ON my_table
COMPOUND TRIGGER
TYPE t_rowids IS TABLE OF ROWID INDEX BY PLS_INTEGER;
g_rowids t_rowids;
BEFORE STATEMENT IS
BEGIN
g_rowids.DELETE;
END BEFORE STATEMENT;
AFTER EACH ROW IS
BEGIN
g_rowids(g_rowids.COUNT+1) := :NEW.ROWID;
END AFTER EACH ROW;
AFTER STATEMENT IS
BEGIN
FOR i IN 1..g_rowids.COUNT LOOP
-- perform processing here
END LOOP;
END AFTER STATEMENT;
END my_table_compound_trg;
Step 4: Alternative Solutions
Use statement-level triggers instead of row-level triggers.
Avoid querying or updating the same table inside the trigger; consider using temporary tables to store intermediate data.
Step 5: Example Scenario
A trigger on the EMPLOYEES table updates another column in the same table. Running an INSERT causes ORA-04091. By converting the row-level trigger to a compound trigger, the error is avoided, and the operation completes successfully.
Conclusion:
ORA-04091 occurs due to attempts to access a table being modified. Using compound triggers, statement-level triggers, or temporary storage helps prevent mutating table errors and ensures smooth database operations.

Comments
Post a Comment