Sub topic 12
The Mutating Table Error (ORA-04091)
This chapter assumes you can write row-level triggers and use :OLD and :NEW. It also assumes you understand transactions and basic PL/SQL exception handling. You will see what ORA-04091 means, which triggers raise it, and how to design around it. The fix with a compound trigger is covered in the next chapter.
What the Error Says
A table is mutating while a statement that changes it is still running. Oracle raises ORA-04091 when a row-level trigger tries to read or change that same table during the statement. The message looks like this:
ORA-04091: table HR.EMPLOYEES is mutating, trigger/function may not see itThe rule exists to protect you from inconsistent results. In the middle of an UPDATE that touches 100 rows, some rows hold new values and others still hold old ones. A query from a row trigger would see that half-finished state. The answer would depend on the order in which Oracle happened to process the rows. Oracle refuses the query instead.
When a Table Counts as Mutating
A table is mutating when one of these statements is changing it:
- An
INSERT,UPDATE, orDELETEon the table. - A
DELETEon a parent table that firesON DELETE CASCADEagainst the table.
The restriction applies to row-level triggers and to functions called from the triggering statement. Statement-level triggers can query the table freely, because they fire before the first row changes or after the last row has changed.
Two exceptions are worth knowing:
- A
BEFORE INSERTorAFTER INSERTrow trigger on a single-rowINSERT ... VALUEScan query its own table. Only one row is involved, so no half-finished state exists.INSERT ... SELECTis not covered by this exception. - Reading
:NEWand:OLDis always allowed. They are the row's own values, not a query against the table.
A Trigger That Fails
Suppose a department may not exceed a payroll of 1,000,000. The obvious trigger sums the salaries after each change:
CREATE OR REPLACE TRIGGER employees_payroll_bad
AFTER UPDATE OF salary ON employees
FOR EACH ROW
DECLARE
l_total NUMBER;
BEGIN
SELECT SUM(salary)
INTO l_total
FROM employees
WHERE department_id = :NEW.department_id;
IF l_total > 1000000 THEN
RAISE_APPLICATION_ERROR(-20002, 'Department payroll limit exceeded');
END IF;
END employees_payroll_bad;
/The trigger compiles without complaint. The error appears only at run time:
UPDATE employees
SET salary = salary * 1.1
WHERE department_id = 50;ORA-04091: table HR.EMPLOYEES is mutating, trigger/function may not see it
ORA-06512: at "HR.EMPLOYEES_PAYROLL_BAD", line 4
ORA-04088: error during execution of trigger 'HR.EMPLOYEES_PAYROLL_BAD'Because the failure is a run-time one, a trigger can pass a test that updates one row and then fail in production on a multi-row update. Test with statements that touch several rows.
The sequence below shows where the failure happens.
When a trigger raises an error, Oracle rolls back the whole triggering statement, not only the current row. Changes made earlier in the transaction by other statements stay in place until you roll back or commit.
Mutating Tables and Constraints
The same restriction applies to constraining tables. A table is constraining when a foreign key on it points to the table being changed. In older releases, a row trigger on a child table could not read the parent while a cascade was in progress. Current releases relax the rule for most foreign key cases. Do not rely on this relaxation. If a trigger works only because of a particular constraint layout, a later schema change can break it.
Why Other Workarounds Fail
Several tempting fixes are either wrong or fragile.
- Autonomous transaction. Adding
PRAGMA AUTONOMOUS_TRANSACTIONto the trigger lets the query run, because it executes in a separate transaction. That transaction cannot see the uncommitted changes of the parent transaction. The query returns stale data and the check gives wrong answers. The autonomous block also has to commit or roll back before it ends, which breaks the atomicity of your statement. - Catching the exception. Wrapping the query in
EXCEPTION WHEN OTHERS THEN NULLhides the error and silently drops the business rule. The data can then violate the rule with no warning. - Package variables with a manual flag. Collecting values in a package from a row trigger and processing them in a statement trigger works. It also requires a separate package, a statement trigger, and cleanup logic that must handle errors and multiple statements in one session. A compound trigger does the same job in one object.
Fix 1: Avoid the Query
The simplest solution is often to stop needing the query. Ask whether the rule can be expressed with only the row's own values.
- A check such as "salary must be between 1000 and 50000" needs only
:NEW.salary. Use aCHECKconstraint instead of a trigger. - A rule that compares old and new values needs only
:OLDand:NEW. The salary decrease check from the earlier chapter is an example. - A running total can be stored in a summary table maintained by deltas: add
:NEW.salary - :OLD.salaryto a row in a different table. Reading and updating another table is allowed.
Here is the delta approach for payroll. The dept_payroll table holds one row per department:
CREATE OR REPLACE TRIGGER employees_payroll_delta
AFTER UPDATE OF salary ON employees
FOR EACH ROW
BEGIN
UPDATE dept_payroll
SET total_salary = total_salary + (:NEW.salary - :OLD.salary)
WHERE department_id = :NEW.department_id;
END employees_payroll_delta;
/A CHECK (total_salary <= 1000000) constraint on dept_payroll then enforces the limit. This trigger has a cost. Concurrent sessions that change salaries in the same department now queue on one summary row, which reduces concurrency. It must also handle inserts, deletes, and department changes, or the summary drifts from the real data.
Fix 2: Defer the Query to a Statement Trigger
When the rule needs a query over the changed table, run the query after the statement finishes. At that point the table is no longer mutating. The pattern has two steps.
- In the row trigger, record what you need (keys, ids, old values) in a collection.
- In the
AFTER STATEMENTsection, loop over the collection and run the query.
Doing this with separate triggers needs a package to hold the collection. A compound trigger keeps both steps and the collection in one object. That is the approach covered in the next chapter, and it is the recommended one.
Fix 3: Use a Different Mechanism
Some rules do not belong in a row trigger at all.
| Situation | Better choice |
|---|---|
| Range or format check on one row | `CHECK` constraint |
| Value must exist in another table | Foreign key |
| Uniqueness across rows | Unique constraint or unique index |
| Cross-row total or count that must always hold | Compound trigger, or a materialized view with a constraint |
| Business rule with many steps | A PL/SQL procedure that is the only way to change the data |
Diagnosing the Error
When you see ORA-04091, check these points in order:
- Read the message. It names the table and, in the error stack, the trigger and line number.
- Find the query or function call at that line. Functions called from the trigger count too, even if the
SELECTis hidden inside them. - Confirm the query reads the same table the triggering statement is changing.
- Decide whether the query is needed. If it is, move it to an
AFTER STATEMENTtiming point.
You can list the triggers that touch a table with this query:
SELECT trigger_name, trigger_type, triggering_event
FROM user_triggers
WHERE table_name = 'EMPLOYEES'
AND trigger_type LIKE '%EACH ROW%';Only row triggers are candidates for this error, so the filter narrows the search.
Summary of Rules
- A row trigger cannot query or modify the table its statement is changing.
- Statement triggers are not restricted.
:NEWand:OLDare always available.- An autonomous transaction or a swallowed exception does not solve the problem. It hides it.
- Prefer constraints and
:NEW/:OLDlogic first. Use a compound trigger when you need to query the table.
Exercise
A row-level AFTER UPDATE trigger on ORDERS counts the other open orders for the same customer with a SELECT COUNT(*) FROM orders. A test that updates one order passes, and an UPDATE that changes ten orders raises ORA-04091. Why does the single-row test pass or fail inconsistently with the ten-row update, and where should the count move?
Show answer
The trigger queries ORDERS, the table the UPDATE is changing, so Oracle raises ORA-04091 whenever a row trigger fires on a statement that is still changing the table. Move the count out of the row trigger. Have the row trigger save the customer ids in a collection, and run the COUNT in an AFTER STATEMENT section (as a compound trigger does), when ORDERS is no longer mutating. Testing with several rows is the only reliable way to catch the error, and an autonomous transaction or WHEN OTHERS handler is not a valid fix.
Exercise
Name two ways to enforce "no department may have a payroll above 1,000,000" without querying EMPLOYEES inside a row trigger, and give one drawback of each.
Show answer
Option 1: maintain a DEPTPAYROLL summary table with a row trigger that adds :NEW.salary - :OLD.salary, and put a CHECK constraint on totalsalary. Drawback: concurrent updates in one department queue on the same summary row, and inserts, deletes, and department moves must also be handled. Option 2: use a compound trigger that collects department ids in the row sections and sums salaries in AFTER STATEMENT. Drawback: the check runs only after the whole statement, so the error rolls back the entire statement, and the trigger is more complex than a constraint.