Sub topic 13
Compound Triggers as the Fix for Mutating Tables
This chapter assumes you can write row-level and statement-level triggers, you know how :OLD and :NEW work, and you have seen ORA-04091 before. It covers the compound trigger, which lets row-level and statement-level logic share state. That shared state is the standard fix for ORA-04091.
The problem in one example
A row-level trigger cannot query or modify the table that its own statement is changing. That table is mutating. Suppose you want to cap the payroll of a department. The obvious version queries employees from a row trigger:
CREATE OR REPLACE TRIGGER employees_payroll_row
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_row;
/Any UPDATE employees SET salary = salary * 1.1 now fails with ORA-04091: table EMPLOYEES is mutating, trigger/function may not see it. Oracle blocks the query because the table is only partly updated while rows are still being processed, so any total would be wrong.
Statement-level triggers do not have this restriction. They fire before the first row or after the last row, when the table is in a consistent state. The difficulty is that a statement trigger has no :NEW and cannot tell which departments were touched. A compound trigger solves this by combining both levels in one object with shared variables.
Structure of a compound trigger
A compound trigger is one trigger with up to four timing-point sections. Each section is a small PL/SQL block. A declaration section before the first section holds variables and types that all sections share.
| Section | Fires | Runs how often | `:OLD` / `:NEW` |
|---|---|---|---|
| `BEFORE STATEMENT` | Before the statement changes any row | Once | Not available |
| `BEFORE EACH ROW` | Before each row is changed | Once per row | Available, `:NEW` is writable |
| `AFTER EACH ROW` | After each row is changed | Once per row | Available, read-only |
| `AFTER STATEMENT` | After all rows are changed | Once | Not available |
You include only the sections you need. The trigger header uses FOR instead of BEFORE or AFTER, and the body starts with COMPOUND TRIGGER.
The standard pattern: collect, then check
The pattern has two steps:
- In the row section, record what you need (keys, old values, new values) in a collection. Do not query the table.
- In the
AFTER STATEMENTsection, query the table once and act on the recorded data.
Here is the payroll check written this way:
CREATE OR REPLACE TRIGGER employees_payroll_ct
FOR UPDATE OF salary ON employees
COMPOUND TRIGGER
TYPE t_dept_ids IS TABLE OF employees.department_id INDEX BY PLS_INTEGER;
g_dept_ids t_dept_ids;
AFTER EACH ROW IS
BEGIN
g_dept_ids(g_dept_ids.COUNT + 1) := :NEW.department_id;
END AFTER EACH ROW;
AFTER STATEMENT IS
l_total NUMBER;
BEGIN
FOR i IN 1 .. g_dept_ids.COUNT LOOP
SELECT SUM(salary) INTO l_total
FROM employees
WHERE department_id = g_dept_ids(i);
IF l_total > 1000000 THEN
RAISE_APPLICATION_ERROR(-20002, 'Department payroll limit exceeded');
END IF;
END LOOP;
END AFTER STATEMENT;
END employees_payroll_ct;
/The query in AFTER STATEMENT is legal because the statement has finished changing rows. If the check fails, the exception propagates and Oracle rolls back the whole triggering statement, including every row it changed.
Improving the example
The first version has three weaknesses. It stores one entry per updated row, so updating 50,000 employees in one department stores 50,000 identical ids and runs 50,000 identical queries. It also ignores inserts, deletes, and department moves. Finally, a department id can be NULL.
Use the department id as the collection index so duplicates collapse. Cover all events, and record both the old and new department:
CREATE OR REPLACE TRIGGER employees_payroll_ct2
FOR INSERT OR UPDATE OF salary, department_id OR DELETE ON employees
COMPOUND TRIGGER
TYPE t_dept_set IS TABLE OF BOOLEAN INDEX BY PLS_INTEGER;
g_depts t_dept_set;
AFTER EACH ROW IS
BEGIN
IF :NEW.department_id IS NOT NULL THEN
g_depts(:NEW.department_id) := TRUE;
END IF;
IF :OLD.department_id IS NOT NULL THEN
g_depts(:OLD.department_id) := TRUE;
END IF;
END AFTER EACH ROW;
AFTER STATEMENT IS
l_dept PLS_INTEGER := g_depts.FIRST;
l_total NUMBER;
BEGIN
WHILE l_dept IS NOT NULL LOOP
SELECT NVL(SUM(salary), 0)
INTO l_total
FROM employees
WHERE department_id = l_dept;
IF l_total > 1000000 THEN
RAISE_APPLICATION_ERROR(-20002,
'Payroll limit exceeded for department ' || l_dept);
END IF;
l_dept := g_depts.NEXT(l_dept);
END LOOP;
END AFTER STATEMENT;
END employees_payroll_ct2;
/Each department is now checked once per statement, however many rows changed. The error message also names the department. :OLD is null on insert and :NEW is null on delete, so the null tests handle all three events.
How the shared state behaves
- State lives for one statement. Oracle creates the variables when the statement starts and discards them when it ends, whether it succeeds or fails. You do not need to reset the collection, and you cannot carry data from one statement to the next.
- State is per session. Two sessions running the same trigger each get their own variables.
- Statement sections always run.
BEFORE STATEMENTandAFTER STATEMENTfire even if the statement matches zero rows. In that case the collection is empty and the loop does nothing, so write your code to cope with that. - Each section has its own exception handler. You can add an
EXCEPTIONblock inside any timing-point section. The declaration section has none. - Memory grows with the rows processed. A row section that stores every row can use a lot of session memory on a large statement. Keep only what the final check needs, or flush the collection in batches.
Other uses
The compound trigger is also good for performance. A row-level audit trigger that inserts into an audit table once per row pays a context switch and a single-row INSERT each time. In a compound trigger you can collect audit records in a collection during AFTER EACH ROW and write them with one FORALL insert in AFTER STATEMENT. A common refinement is to flush when the collection reaches a fixed size, such as 1,000 rows, using IF g_rows.COUNT >= 1000 THEN flush; END IF;. Do the same flush once more in AFTER STATEMENT for the remainder.
You can also use BEFORE STATEMENT to initialise state, for example to read a configuration value once and reuse it in every row.
Limits and gotchas
- A compound trigger belongs to one table (or view) and handles DML only. For views, the only row section allowed is
INSTEAD OF EACH ROW. - The compound trigger cannot call itself recursively through its own state. If an
AFTER STATEMENTsection runs DML on the same table, that DML starts a new statement with fresh state, and the trigger fires again. Guard against loops. - Querying the table from
AFTER EACH ROWstill raises ORA-04091. Only the statement sections are safe, so do all queries there. - Writing to the table from
AFTER STATEMENTis allowed, but you should rarely need it. Prefer aBEFORE EACH ROWsection that sets:NEWvalues. - Triggers that fire for the same event as a compound trigger follow the usual
FOLLOWSordering rules. The compound trigger counts as a single trigger for ordering. COMMITandROLLBACKremain forbidden in every section, as in any trigger.
Exercises
Exercise
A row-level AFTER UPDATE trigger on orders sums line_total from orders for the same customer and fails with ORA-04091. Describe how you would restructure it as a compound trigger. Say which section collects data, which section queries, and what you store.
Show answer
In AFTER EACH ROW, store only the customer_id of each changed row, preferably as the index of an associative array so duplicates collapse. Do no queries there. In AFTER STATEMENT, loop over the stored customer ids, run the SUM query against orders once per customer, and raise an error if the rule is broken. The query is legal in AFTER STATEMENT because the statement has finished and the table is no longer mutating.
Exercise
You run UPDATE employees SET salary = salary WHERE 1 = 0 against the compound trigger employeespayrollct2. No rows match. Does the AFTER STATEMENT section run, and what happens in it?
Show answer
Yes, it runs once, because statement-level sections fire even when no rows are affected. The collection gdepts is empty, so gdepts.FIRST returns NULL, the WHILE loop body never executes, and the section ends without querying or raising an error.