Creating Triggers  «Prev  Next»

Lesson 2What is a trigger?
ObjectiveDefine an Oracle database trigger and explain its event, timing, and firing level.

What Is an Oracle Database Trigger?

A database trigger is a named stored program that Oracle invokes automatically in response to a configured database event. For example, an UPDATE can cause a trigger to record the previous and current salary for each affected employee. The application submits the UPDATE; Oracle performs the associated trigger work without requiring a separate call from the application.

In Oracle AI Database 26ai, understanding a trigger begins with three questions: which event activates it, when its code runs, and whether it processes a statement or an individual row. These attributes explain both the trigger's purpose and its effects. They also help you recognize when a declarative constraint or an explicitly called procedure would express a requirement more clearly.

A trigger must be enabled to fire. Creating its definition does not perform its future business operation, and applications do not invoke it by name as they invoke a procedure. Oracle's trigger overview describes this automatic invocation model.

Identify the event, timing, and firing level

Consider a trigger whose header contains AFTER UPDATE OF salary ON demo_trigger_employees FOR EACH ROW. Each part has a separate meaning:

Three attributes of the salary-history trigger
AttributeMeaning in this example
EventAn UPDATE involving the salary column of demo_trigger_employees.
TimingThe trigger runs after an affected row has been updated.
Firing levelFOR EACH ROW makes this a row trigger, processing each affected row.

The table name identifies the object associated with the event. The trigger body contains the action Oracle performs when that event reaches the selected timing point. In this lesson, that action is an INSERT into a history table. The original UPDATE and the history INSERT are different SQL operations connected by the trigger.

UPDATE OF salary does not mean that the salary's value must differ from its previous value. A statement can set salary to itself and still activate the trigger. If the requirement is to record actual value changes, the body must compare the old and new values. This distinction prevents misleading history entries.

Distinguish statements from transactions

A simple BEFORE or AFTER trigger on a table is a statement trigger when its definition omits FOR EACH ROW. In ordinary execution, it runs once at its selected timing point for the qualifying statement. A row trigger instead runs for each affected row. If one UPDATE affects twenty employees, a row trigger processes twenty rows, while a statement trigger handles the statement once.

A statement is not a transaction. One transaction can contain several INSERT, UPDATE, and DELETE statements before the application commits or rolls back. Therefore, describing statement triggers as firing once per transaction gives the wrong result whenever a transaction contains more than one qualifying statement.

A successful UPDATE that matches no rows still has statement-level timing points, but there is no affected row for a row trigger to process. This difference is useful when testing empty-result conditions. These descriptions explain normal execution, not a guarantee that internal statement restarts can never repeat trigger work. Oracle's design guidelines also caution against assumptions about row order and repeated execution.

Understand firing order

For ordinary table DML, BEFORE STATEMENT work occurs first. As Oracle processes each affected row, BEFORE EACH ROW work precedes that row's modification and AFTER EACH ROW work follows it. AFTER STATEMENT work occurs after statement-level row processing. This does not mean Oracle processes every row's BEFORE trigger before starting any row's AFTER trigger.

Creation time does not establish the order among several triggers at the same timing point. An older trigger is not automatically first, and AFTER triggers do not execute in reverse creation order. Where eligible conventional triggers require a relative order, FOLLOWS can express that relationship. The PRECEDES clause is restricted to reverse crossedition triggers, a specialized edition-based redefinition feature.

Keep related operations together when their sequence is essential, and avoid relying on an undocumented ordering relationship. See Oracle's firing-order rules for the supported ordering controls.

Recognize the main trigger categories

A simple DML trigger has one timing point. A compound DML trigger can contain several timing sections and shared state for the triggering statement. That structure can collect row information and process it later, for example when accumulating history records for bulk insertion. Moving suitable work to an AFTER STATEMENT section can also help address a mutating-table problem; merely using the word COMPOUND does not make unsafe logic correct.

An INSTEAD OF DML trigger supplies the implementation of a modification through a noneditioning view, including supported nested-table columns of such views. It is useful when the desired view operation needs custom handling. Its use is not limited to views that Oracle considers inherently non-updatable.

Schema and database triggers respond to supported DDL or database events, such as object creation or a session logon. Their available events and timing combinations differ from ordinary table DML. A row-level classification describes how a trigger fires; compound describes its structure. These are not interchangeable classifications. Oracle's DML trigger reference develops these distinctions.

Read the current row through OLD and NEW

A row trigger can use the :OLD and :NEW pseudorecords to inspect values associated with the current row. They do not hold the complete set of rows changed by the statement.

Row values available for each DML event
EventOLD fieldsNEW fields
INSERTNULLNew row values
UPDATEPrevious row valuesUpdated row values
DELETEDeleted row valuesNULL

OLD fields are not writable. A BEFORE INSERT or UPDATE row trigger can assign individual NEW fields before the row is stored. An AFTER row trigger can inspect the resulting values but cannot assign NEW fields. Statement triggers do not have these current-row values.

Use a colon before the pseudorecord name inside the trigger body, as in :NEW.salary. In an optional trigger WHEN condition, omit that colon. These are context-sensitive syntax rules, explained in Oracle's pseudorecord documentation.

Create an independent salary-history example

The following demonstration records salary changes in a database table. It does not write an external log file or require the HR sample schema. Use a separate practice schema, unused object names, CREATE TABLE and CREATE TRIGGER privileges, and sufficient tablespace quota. Keep the demonstration separate from the course's business tables.

Complete the table and trigger definitions before beginning the transaction test. Oracle DDL performs implicit commits, so creating objects inside an unfinished application transaction is not a safe substitute for an isolated practice session. For the later DML test, use one dedicated connection with client autocommit disabled.

CREATE TABLE demo_trigger_employees (
    employee_id NUMBER PRIMARY KEY,
    salary      NUMBER(10,2) NOT NULL CHECK (salary >= 0)
);

CREATE TABLE demo_salary_audit (
    employee_id NUMBER NOT NULL,
    changed_at  TIMESTAMP WITH TIME ZONE NOT NULL,
    old_salary  NUMBER(10,2) NOT NULL,
    new_salary  NUMBER(10,2) NOT NULL
);

The primary key identifies each demonstration employee. The salary constraints require a non-NULL, nonnegative value. The history table permits multiple records for the same employee because that employee can receive several salary changes. Its employee_id column is not a unique audit-event identifier.

The example deliberately keeps the history structure small. A production history design would also decide how to identify events, attribute changes to users, control access, and retain records. Those decisions belong to the application's requirements rather than the definition of a trigger.

Define the row trigger

CREATE OR REPLACE TRIGGER demo_salary_audit_trg
    AFTER UPDATE OF salary ON demo_trigger_employees
    FOR EACH ROW
BEGIN
    IF :NEW.salary <> :OLD.salary THEN
        INSERT INTO demo_salary_audit
            (employee_id, changed_at, old_salary, new_salary)
        VALUES
            (:OLD.employee_id, SYSTIMESTAMP,
             :OLD.salary, :NEW.salary);
    END IF;
END;
/

The event is an UPDATE involving salary, the timing is AFTER each affected row, and the body records the change only when the two salary values differ. The INSERT names its target columns explicitly, making the relationship between each column and value easy to review.

Because salary is NOT NULL, the inequality is sufficient here. With nullable data, a simple inequality would not detect every transition involving NULL; that design would need explicit NULL handling. The trigger records the employee identifier from the original row. The demonstration changes salary only, so employee identifiers remain unchanged.

No query against the changing employee table is needed. OLD and NEW already provide the relevant values. Avoiding that unnecessary query also avoids introducing the classic row-trigger mutating-table problem into this example.

The final slash is a script execution command in clients such as SQL*Plus and SQLcl, not part of the PL/SQL body sent through a database API. For triggers with cross-schema dependencies, the owner needs appropriate privileges granted directly rather than obtained only through roles. See CREATE TRIGGER for prerequisites and syntax.

Inspect compilation diagnostics

Before running the test, check the trigger's compiler diagnostics. An enabled invalid trigger can prevent the DML that would activate it from succeeding. The dictionary query below distinguishes errors from warnings:

SELECT attribute, line, position, text
FROM user_errors
WHERE name = 'DEMO_SALARY_AUDIT_TRG'
  AND type = 'TRIGGER'
ORDER BY sequence;

Resolve entries marked ERROR before proceeding; review WARNING entries according to their messages. A valid object can have warnings, so the mere presence of a diagnostic row is not proof of a compilation failure. With no recorded diagnostics, the query returns no rows. The errors dictionary reference describes these columns and the related USER_ERRORS view.

Compilation and enablement answer different questions. A trigger can have valid compiled code while deliberately disabled. Conversely, an enabled trigger can encounter compilation or execution problems. The trigger dictionary views, including USER_TRIGGERS for your own triggers, expose the triggering event, associated object, trigger type, and ENABLED or DISABLED status. Inspect those properties when behavior differs from the definition you expected to install.

Test changes, unchanged values, and rollback

Run the following commands after the DDL, on the same connection, with autocommit disabled. The initial inserts establish two employees. The savepoint separates those inserts from the salary updates, allowing the test to undo the changes while temporarily retaining its starting rows.

INSERT INTO demo_trigger_employees (employee_id, salary)
VALUES (1, 1000);

INSERT INTO demo_trigger_employees (employee_id, salary)
VALUES (2, 2000);

SAVEPOINT before_salary_test;

UPDATE demo_trigger_employees
SET salary = salary + 100
WHERE employee_id IN (1, 2);

UPDATE demo_trigger_employees
SET salary = salary
WHERE employee_id = 1;

UPDATE demo_trigger_employees
SET salary = salary + 100
WHERE employee_id = 99;

SELECT employee_id, old_salary, new_salary
FROM demo_salary_audit
ORDER BY employee_id;

ROLLBACK TO before_salary_test;

SELECT employee_id, salary
FROM demo_trigger_employees
ORDER BY employee_id;

SELECT COUNT(*) AS audit_rows
FROM demo_salary_audit;

ROLLBACK;

The first UPDATE affects two rows and produces two history records. The second still invokes the salary trigger for employee 1, but the unchanged value makes its IF condition false. The third UPDATE matches no employee and invokes no row trigger. No statement trigger is defined in this demonstration.

Before the savepoint rollback, the history query should return the following values. These are expected results derived from the example, not output captured from an executed Oracle session:

Expected salary-history rows before rollback
employee_idold_salarynew_salary
110001100
220002100

ROLLBACK TO restores salaries to 1000 and 2000 and removes both history records, making audit_rows zero. The final ROLLBACK also removes the uncommitted employee inserts and ends the transaction. The tables and trigger remain because their DDL was completed earlier. Do not insert a COMMIT, DDL command, or autocommit step between the savepoint and its rollback. Oracle's rollback reference explains the distinction between partial rollback and ending a transaction.

Read each query's output at the point where it occurs in the script. A query after the final rollback cannot reproduce the earlier history rows because the test intentionally removed them. You can run the DML test again against these now-empty demonstration tables without recreating the objects. If a previous run stopped partway through, inspect and resolve that session's transaction before restarting; do not assume the starting rows are absent.

When an expected history entry is missing, check the conditions in order: the connection and schema, the trigger's enabled state, its event definition, the rows matched by the UPDATE, and finally the value comparison. A successful UPDATE message alone does not establish that a value changed. Likewise, two affected rows do not prove that two entries remain after a later rollback. This method separates a triggering problem from an intentional filtering condition or transaction outcome.

Creating or replacing the trigger does not reconstruct earlier salary changes. The history begins with qualifying operations while the trigger is enabled and its work succeeds. If existing data needs a historical baseline, that requires a separately designed migration or opening snapshot. Do not label such a snapshot as a sequence of changes that the trigger actually observed.

Keep trigger work within the transaction

This is an ordinary nonautonomous DML trigger. Its history INSERT participates in the caller's transaction: AFTER means after the row operation, not after commit. Until the caller commits, the history changes remain subject to rollback along with the salary changes.

An unhandled error in this simple trigger normally fails the triggering statement and undoes that statement's trigger effects. It does not imply that every earlier successful statement in the transaction is automatically undone. System triggers have additional exceptions to broad rollback claims; Oracle documents them under trigger exception handling.

Do not place COMMIT or ROLLBACK inside this trigger. Calling a procedure does not evade the trigger's transaction restrictions. An autonomous transaction has different semantics and would change the relationship this example demonstrates. It is not a routine repair for an incorrectly designed history trigger. Oracle's trigger restrictions also explain why a row trigger cannot freely query or modify its mutating table.

Choose the right mechanism for the requirement

Use declarative constraints for rules they express. A foreign key is generally clearer than trigger code for an ordinary parent-child relationship. NOT NULL and CHECK express the example's salary requirements directly. A timestamp default may handle an insertion requirement, while a virtual column can express an appropriate derived value without maintaining a duplicate stored value through a trigger.

The history example is also different from security auditing. It does not retain rolled-back attempts, prove who made a change, or replace Oracle Unified Auditing. Access privileges and row-access policies should provide their intended security controls. Summary-table maintenance likewise requires deliberate handling of concurrent changes; automatic firing alone does not prove correctness.

Oracle 26ai adds another option for suitable integrity rules: SQL assertions, introduced in Release Update 23.26.1. They can describe supported rules across rows or tables and reduce procedural validation. Check the installed release update and the restrictions in CREATE ASSERTION. An assertion validates a condition; it does not replace a trigger whose purpose is to insert change-history records.

Oracle 26ai also documents native PL/SQL VECTOR support, including use in trigger pseudorecords, subject to type-specific restrictions. That capability does not alter the event, timing, or transaction concepts demonstrated here.

You can now identify what activates a trigger, determine its firing level, interpret its row values, and test its transactional effects. The next lesson, comparing triggers and procedures, examines how automatic database behavior differs from an explicitly invoked operation.


SEMrush Software 2 SEMrush Banner 2