A database trigger associates stored PL/SQL code with a database event. When the specified event occurs, Oracle Database invokes the enabled trigger automatically. For example, an application might update an item's price while a trigger supplies a timestamp for the affected row. The application issues the UPDATE; the database performs the associated trigger work as part of processing that operation.
In this Oracle AI Database 26ai module, you will learn to choose an appropriate trigger event, understand the values available to the trigger, and test its effects. The central design question is whether an action belongs automatically with an operation on the data. A trigger can make that relationship consistent across applications, but it also introduces behavior that the caller's SQL statement does not show directly.
By the end of the module, you should be able to:
:OLD and :NEW appropriately.This introduction establishes the design and transaction concepts behind those tasks. A short example then connects the trigger definition to the SQL that makes it fire. These capabilities are established PL/SQL features supported in Oracle 26ai, rather than features introduced specifically for this release.
An ordinary procedure exposes an operation that a caller invokes explicitly, often supplying parameters. A trigger instead has a configured event and timing point. You do not call the trigger by name to perform its work; you issue the relevant database operation. Creating the trigger stores its definition. Later execution of its triggering event causes it to fire.
For an item-maintenance procedure, a developer might choose which applications can call it and what arguments it accepts. A trigger on the underlying table responds when the configured operation reaches that table, including through another permitted application. This makes the table operation the point of attachment. It does not eliminate the need to control permissions or document the action.
A trigger can call a procedure to keep shared logic in one place. That procedure still runs within the restrictions of the trigger's execution context. Moving a COMMIT into a called procedure, for example, does not make it permissible in an ordinary trigger. Oracle's trigger overview explains automatic invocation and the objects on which triggers can be defined.
This module concentrates on DML triggers associated with tables or views. Their events include INSERT, UPDATE, and DELETE. Oracle also supports triggers for selected DDL and database events, such as certain schema changes or logons. Those are separate administrative use cases with their own restrictions. Oracle Forms application triggers are another subject and should not be confused with database triggers.
For a simple table DML trigger, make two distinct choices: when it runs relative to the operation and whether its work belongs to the statement or each affected row.
| Timing point | When the body runs |
|---|---|
| BEFORE statement | Before the triggering statement processes its rows. |
| BEFORE each row | Before the operation on each affected row. |
| AFTER each row | After the operation on each affected row. |
| AFTER statement | After the triggering statement has processed its rows. |
A simple row trigger includes FOR EACH ROW. In an ordinary UPDATE affecting ten rows, its body runs for those affected rows. A statement trigger operates at statement scope, including when the statement affects no rows. Neither description means once per transaction: one transaction can contain several statements. See Oracle's DML trigger reference for the timing model.
AFTER does not mean after COMMIT. An AFTER trigger can finish successfully while the transaction remains uncommitted. The caller can subsequently roll back. Keep this distinction in mind when a trigger records changes or prepares information for another system.
Before writing trigger code, identify the actual rule. A primary key identifies rows, a foreign key expresses a supported relationship, and a unique constraint prevents prohibited duplicate key values. NOT NULL rejects missing values. CHECK evaluates a condition on the row. These are declarative integrity features: the rule is expressed directly in the database definition.
Suppose an item's price must be present and nonnegative. A NOT NULL declaration together with CHECK (unit_price >= 0) expresses that requirement without a trigger. CHECK alone is insufficient for excluding NULL because an unknown condition is not the same as a false condition. Oracle documents these rules in its constraint reference.
A different requirement might say that every permitted INSERT or UPDATE must refresh a timestamp. That describes an action associated with an event. The example below uses a trigger for that action while leaving the price rule to constraints. Keeping the responsibilities separate makes the design easier to explain and the tests easier to interpret.
Do not treat a custom change-history trigger as a complete security-auditing system. Its records need a defined purpose, access controls, retention policy, and transaction behavior. Database privileges remain the mechanism for deciding which operations an account may perform.
A row trigger can inspect the row it is processing through pseudorecords. The default names are OLD and NEW; references to their fields in the PL/SQL body use a leading colon. They resemble records but have specific restrictions, so the term pseudorecord is more accurate than a general-purpose record variable.
| Event | :OLD fields | :NEW fields |
|---|---|---|
| INSERT | NULL | New values |
| UPDATE | Values before the update | New values |
| DELETE | Values before deletion | NULL |
A BEFORE row trigger for INSERT or UPDATE can assign individual NEW fields. An AFTER row trigger cannot change them, and OLD fields are not writable. These pseudorecords describe one row; they are not a collection of every row affected by the statement. They are also unavailable as row values in a statement-level trigger. The later lesson on special trigger variables develops these distinctions using Oracle's pseudorecord rules.
Use a separate practice schema for this example. It needs CREATE TABLE and CREATE TRIGGER privileges and sufficient tablespace quota. The names below must be unused. These demonstration objects are independent of the course's House-O-Pets tables.
Complete the setup before the transaction test. Oracle DDL performs implicit commits, so creating or replacing database objects is not a way to experiment inside an uncommitted application transaction. Start with a dedicated practice session and leave client autocommit disabled for the later INSERT and UPDATE.
CREATE TABLE trigger_demo_items (
item_id NUMBER PRIMARY KEY,
unit_price NUMBER(10,2) NOT NULL CHECK (unit_price >= 0),
changed_at TIMESTAMP WITH TIME ZONE
);
The table contains an identifier, a constrained price, and a timestamp column. Now define the trigger:
CREATE OR REPLACE TRIGGER trg_demo_items_changed
BEFORE INSERT OR UPDATE ON trigger_demo_items
FOR EACH ROW
BEGIN
:NEW.changed_at := SYSTIMESTAMP;
END;
/
The heading names the trigger, identifies its events and target table, and selects row scope. The body assigns a value to the current row's changed_at field. There is no second UPDATE against the table. The assignment supplies the value as the original operation processes the row.
SYSTIMESTAMP returns a timestamp including fractional seconds and a time zone, matching the column's datatype. The value records when the trigger evaluates the expression, not when the transaction eventually commits. It does not identify the user or preserve previous versions of the row. See the SYSTIMESTAMP reference for its return type and display considerations.
The trigger also overwrites a changed_at value supplied by the caller. That is intentional here: the database controls this field. A default used only when inserting a row would not implement the same update behavior. Explain this contract to application developers instead of assuming that an automatically maintained column is self-explanatory.
The slash on its own line is a script-client command in SQL*Plus or SQLcl-style execution. It submits the buffered PL/SQL unit; it is not part of the stored trigger body. Use the execution mode appropriate to your client. Oracle's CREATE TRIGGER reference describes the definition and privileges.
Check compilation before testing the data changes. A stored trigger definition can contain compilation errors, so the presence of its name is not sufficient evidence that the example is ready. For the unquoted trigger name used here, inspect the current schema's diagnostic information:
SELECT line, position, text
FROM user_errors
WHERE name = 'TRG_DEMO_ITEMS_CHANGED'
AND type = 'TRIGGER'
ORDER BY sequence;
The result identifies diagnostic locations and messages. Read the reported issue, correct the definition, and compile it again before proceeding. This query examines metadata; it does not fire the trigger. If it returns no rows, also confirm that you created the expected object in the expected schema rather than assuming that an absent diagnostic proves the object exists. Oracle documents this view in USER_ERRORS.
Keep compilation, successful firing, and correct application behavior as separate checks. A trigger may compile while implementing the wrong event or assigning the wrong column. Conversely, a valid trigger cannot make an application statement succeed when that statement violates a constraint or lacks permission. The test below deliberately uses one known row so you can connect each operation with a specific observation.
After setup, stay in the same practice session with autocommit disabled. Establish a savepoint, insert one row, and query the stored values. Then update its price and read the row again:
SAVEPOINT trigger_demo_start;
INSERT INTO trigger_demo_items (item_id, unit_price)
VALUES (1, 19.95);
SELECT item_id, unit_price, changed_at
FROM trigger_demo_items
WHERE item_id = 1;
UPDATE trigger_demo_items
SET unit_price = 24.95
WHERE item_id = 1;
SELECT item_id, unit_price, changed_at
FROM trigger_demo_items
WHERE item_id = 1;
ROLLBACK TO trigger_demo_start;
SELECT COUNT(*) AS remaining_demo_rows
FROM trigger_demo_items
WHERE item_id = 1;
Under the stated setup, the first query shows price 19.95 and a populated timestamp. The second shows 24.95 and a timestamp assigned during the UPDATE. Operations close together need not display visibly different timestamps, so a difference in printed values is not the only useful observation.
The final count should be zero: rolling back to the savepoint undoes both the inserted row and the later update. The table and trigger definitions remain because their setup occurred earlier. ROLLBACK TO does not end the transaction; finish the practice transaction explicitly when you are done. Oracle's ROLLBACK documentation distinguishes partial rollback from rolling back the whole transaction.
These are expected results for the example, not output captured from a database run. Inspect the values in your own environment. If the trigger does not compile or the DML fails, resolve that error before interpreting the returned data.
An automatic commit between these statements erases the savepoint. If ROLLBACK reports that the savepoint is unavailable, check the client's transaction settings before concluding that the trigger behaved incorrectly.
For the ordinary, non-autonomous DML triggers taught here, database changes performed by the trigger belong to the triggering transaction. A log row inserted by such a trigger is rolled back with the transaction. That is appropriate when the log represents completed business changes, but it differs from a separate record of attempted actions.
An unhandled error in a simple DML trigger normally fails the triggering statement and rolls back that statement's effects, including its trigger work. This does not necessarily undo successful statements issued earlier in the transaction. The application still needs an explicit error-handling and transaction policy. Oracle describes the usual behavior and special cases in exception handling in triggers.
Do not put COMMIT, ROLLBACK, or DDL in the ordinary trigger body. Autonomous transactions are a separate advanced facility with a different relationship to the caller's work. They should not be introduced simply to preserve an alert about a business change that might later disappear.
A trigger can detect a condition while data changes, but detecting a condition does not establish that the change will commit. Consider a large transaction amount. If a row trigger sends an email immediately and the application later rolls back, the recipient can receive a message about a change that never became permanent. Database rollback cannot recall a message already handed to an SMTP server.
Direct notification calls also make the user's DML depend on network availability and mail-service behavior. A statement affecting many qualifying rows can make many calls. These are reasons to define the delivery design separately rather than embedding a complete notification service in each row operation.
A useful design is to record an event in an outbox table within the business transaction, then have a separate worker process committed events. Rollback removes the uncommitted event together with the business change. The worker needs retry handling and protection against duplicate delivery; an outbox alone does not guarantee that an external message is delivered exactly once.
Oracle's notification packages have different contracts. DBMS_ALERT supports registered applications waiting for named alerts. Its signals become available after the signalling transaction commits; rollback cancels them. A newer pending alert can replace an older one, so it is not a durable record of every event.
DBMS_PIPE provides intersession messaging independent of the transaction. A pipe message is therefore not confirmation of a commit. UTL_MAIL sends mail through SMTP and has installation, configuration, and network-access prerequisites. Neither package automatically creates an application notification workflow. Choose a mechanism according to what the recipient must know and when it must know it.
Review trigger code as part of the operation that fires it. A statement that looks inexpensive can perform additional reads, writes, and calls through its triggers. Measure representative multirow operations, and document the tables and subprograms on which the trigger depends. Avoid using a row-by-row success test as proof that a large application update will behave well.
A simple row trigger is generally restricted from querying or modifying the table currently being changed by its triggering statement. This is the mutating-table problem. The timestamp example avoids it by assigning the current NEW field rather than issuing another UPDATE. Oracle's trigger restrictions explain the rule and more advanced approaches.
A trigger may handle INSERT, UPDATE, and DELETE together and distinguish the operation with INSERTING, UPDATING, or DELETING. That alone does not make it a compound trigger. Compound DML triggers provide separate timing-point sections with shared state. Learn the simpler event and row-value model first, then consider whether a more elaborate structure solves a specific problem.
For each trigger you study, identify the event, timing point, firing level, values read or assigned, and expected rollback behavior. Then test the relevant cases: a successful change, no matching rows, multiple affected rows, an invalid value, and a rollback. Confirm that constraints reject the data they are responsible for and that the trigger performs only its intended action.
Keep the trigger definition, test statements, and expected observations together. This makes implicit behavior reviewable when another developer changes the table or its application. Oracle's design guidelines provide further considerations for focused trigger code.
The next lesson defines a database trigger more precisely. You will then compare triggers with procedures, work with OLD and NEW values, and build triggers for individual and combined DML events.