Database Triggers & Mutating Table Protection

Database Triggers & Mutating Table Protection in Oracle Database: Triggers execute automatically in response to DDL, DML, or database events.

Triggers execute automatically in response to DDL, DML, or database events. While powerful for auditing and integrity checks, poorly architected triggers frequently cause the dreaded ORA-04091 error.


Trigger Execution Timing & Pseudo-Records

Trigger TypeWhen FiredScopeCommon Use Case
BEFORE ROWPrior to updating table blockFOR EACH ROWValue sanitization, assigning default UUIDs
AFTER ROWImmediately after block updateFOR EACH ROWWriting immutable audit ledger entries
INSTEAD OFIntercepts DML on ViewsView levelEnabling updates on complex multi-table joins
AFTER STATEMENTOnce after entire batch finishesStatement levelNotification, bulk counter reconciliation
-- Immutable Audit Trigger using :OLD and :NEW
CREATE OR REPLACE TRIGGER trg_audit_customer_credit
AFTER UPDATE OF credit_limit ON corporate_accounts
FOR EACH ROW
BEGIN
    INSERT INTO credit_limit_audit (
        account_id,
        previous_limit,
        new_limit,
        modified_by,
        modified_at
    ) VALUES (
        :OLD.account_id,
        :OLD.credit_limit,
        :NEW.credit_limit,
        SYS_CONTEXT('USERENV', 'SESSION_USER'),
        SYSTIMESTAMP
    );
END;
/

The Mutating Table Problem (ORA-04091)

A table is considered mutating when it is currently being modified by a DML statement. If a row-level trigger on table T attempts to query table T, Oracle throws ORA-04091: table is mutating, trigger/function may not see it, because the database cannot guarantee a consistent read while rows are in-flight.


Modern Solution: Compound Triggers

Prior to Oracle 11g, solving mutating errors required cumbersome global temporary tables or package state variables. Oracle introduced Compound Triggers to resolve this cleanly by defining multiple timing sections sharing a common memory scope:

CREATE OR REPLACE TRIGGER trg_enforce_dept_salary_cap
FOR INSERT OR UPDATE OF salary ON employees
COMPOUND TRIGGER

    -- Shared state across all phases of the statement execution
    TYPE t_dept_salaries IS TABLE OF NUMBER INDEX BY PLS_INTEGER;
    v_dept_totals t_dept_salaries;

    -- Phase 1: Fires once before the statement touches any rows
    BEFORE STATEMENT IS
    BEGIN
        -- Clear state
        v_dept_totals.DELETE;
    END BEFORE STATEMENT;

    -- Phase 2: Fires for every row; records affected departments without querying the mutating table
    AFTER EACH ROW IS
    BEGIN
        v_dept_totals(:NEW.department_id) := 1;
    END AFTER ROW;

    -- Phase 3: Fires after all rows have been updated.
    -- Table is NO LONGER MUTATING! Safe to query!
    AFTER STATEMENT IS
        v_total_sal NUMBER;
        v_dept_id   PLS_INTEGER;
    BEGIN
        v_dept_id := v_dept_totals.FIRST;
        WHILE v_dept_id IS NOT NULL LOOP
            SELECT SUM(salary) INTO v_total_sal
            FROM employees WHERE department_id = v_dept_id;

            IF v_total_sal > 5000000 THEN
                RAISE_APPLICATION_ERROR(-20004, 'Department salary budget exceeded: ' || v_dept_id);
            END IF;

            v_dept_id := v_dept_totals.NEXT(v_dept_id);
        END LOOP;
    END AFTER STATEMENT;

END trg_enforce_dept_salary_cap;
/

Exercises

  1. Create an INSTEAD OF trigger on a complex view joining orders and order_items that distributes updates to the respective underlying tables.
  2. Write an audit trigger that captures deleted records into an archive table along with the host IP address of the deleter.
  3. Explain why checking foreign key constraints via triggers is prone to concurrency bugs compared to declarative constraints.