Creating Triggers  «Prev  Next»

Lesson 6Combining DML events in one trigger
ObjectiveBuild and test one Oracle 26ai trigger that handles INSERT, UPDATE, and DELETE.

Combine INSERT, UPDATE, and DELETE in One Oracle Trigger

A table can need related behavior for several kinds of change. New products might require price validation, updates might require the same validation plus a comparison with the previous price, and deletions might copy the removed values to a history table. One Oracle PL/SQL trigger can handle these events while sharing the logic that applies to more than one operation.

This lesson builds a complete example for Oracle AI Database 26ai. You will create isolated practice tables, define a trigger for all three DML events, inspect compilation diagnostics, and test successful operations, rejected changes, and rollback. The examples use familiar product-price columns without replacing the Pet Store course tables or their existing triggers. Results described below are expected outcomes; the examples were reviewed against Oracle documentation, not executed against an Oracle database for this article.

Read the trigger definition in five parts

Oracle 26ai row-level trigger structure with INSERT, UPDATE, and DELETE events, conditional predicates, and row-versus-statement firing scope.
The diagram shows a teaching skeleton. Its NULL statements are placeholders for application logic. The worked example below supplies shared validation, an UPDATE-specific rule, and transactional DELETE history.

The trigger name identifies the stored program. BEFORE or AFTER selects its timing, while INSERT OR UPDATE OR DELETE selects the triggering events. The ON clause identifies the table, and FOR EACH ROW makes the body run for individual affected rows. Finally, conditional predicates select the appropriate statements inside the body. The CUSTOMER name in the diagram is illustrative; the practice example uses PRODUCT_TRIGGER_DEMO.

A simple trigger has one timing point. With FOR EACH ROW, BEFORE means before each row operation; omitting that clause makes it a statement trigger. Statement scope means once per triggering statement, not once per transaction. Combining events does not make the definition a compound trigger, which has separately defined timing-point sections. These distinctions are documented in Oracle's DML trigger reference.

Identify the event and choose the correct row values

INSERTING, UPDATING, and DELETING are conditional predicates. Each is true for its corresponding event. Use them in IF or CASE expressions when the trigger must distinguish new rows, changed rows, and removed rows. They do not describe three variations of an UPDATE operation.

Event-specific information available to this row trigger
EventPredicateOLD fieldsNEW fields
INSERTINSERTINGNULLProposed inserted values
UPDATEUPDATINGValues before the updateProposed updated values
DELETEDELETINGValues being removedNULL

Inside the body, refer to fields as :OLD.sale_price and :NEW.sale_price. On DELETE, validate or record OLD values rather than treating NEW as a replacement row. On UPDATE, NEW includes unchanged column values as well as assigned ones. Oracle describes these correlation names and pseudorecords separately from ordinary local variables.

The more specific predicate UPDATING('SALE_PRICE') detects an UPDATE targeting that column. It does not establish that the stored value changed: assigning a column to itself still targets it. Compare OLD and NEW when the rule concerns a value transition, and account explicitly for NULL.

Define the business rules before writing PL/SQL

For this practice example, INSERT and UPDATE reject a known sale price below a known store cost. Equality is allowed. UPDATE also rejects a decrease from one known sale price to another. DELETE copies the old product values into a separate history table. The no-price-reduction rule is a teaching assumption, not a requirement imposed by Oracle or a general rule for retail systems.

Both price columns remain nullable, matching the policy discussed in the preceding lesson. A missing amount is not zero. If either operand is NULL, the corresponding comparison is skipped. Consequently, changing a known price to NULL is allowed by this example. If a real application requires both amounts, define NOT NULL constraints rather than assuming this trigger supplies that requirement.

This NULL policy also limits what the no-reduction rule guarantees. A caller could change a known price to NULL and later assign a lower known price; neither step compares two known prices. If that transition must be prohibited, revise the policy explicitly, for example by requiring a price and validating existing data before adding the constraint. Do not describe the current example as an unconditional guarantee that a product's price can never decrease across its history.

Keep the two validations distinct. A proposed price of 14 can be above a cost of 10 yet still violate a rule against reducing an existing price of 16. Conversely, increasing only the cost to 17 can violate the price-versus-cost rule even though the UPDATE does not mention SALE_PRICE. The trigger therefore covers all UPDATEs, not only updates of the price column.

Create two isolated practice tables

Use a dedicated learning schema with CREATE TABLE and CREATE TRIGGER privileges and adequate tablespace quota. The following names must be unused. Do not drop existing objects to make the script succeed, and do not substitute the live PRODUCT table without first examining its constraints, data, and triggers. The history table intentionally has no foreign key back to the product row being deleted.

CREATE TABLE product_trigger_demo (
    product_id NUMBER PRIMARY KEY,
    store_cost NUMBER(10,2),
    sale_price NUMBER(10,2)
);

CREATE TABLE product_delete_demo (
    product_id NUMBER,
    store_cost NUMBER(10,2),
    sale_price NUMBER(10,2),
    deleted_at TIMESTAMP WITH TIME ZONE
);

PRODUCT_TRIGGER_DEMO holds the current rows. PRODUCT_DELETE_DEMO stores copies of deleted values and a timestamp. Its role is transactional history; it is not an immutable security audit trail. Keeping these tables separate also lets the row trigger record OLD fields without querying the table currently undergoing the triggering change.

Complete all table and trigger DDL before beginning the savepoint tests. Oracle DDL can commit pending work, so do not interleave CREATE, ALTER, or DROP commands with a test that depends on rollback. Use a clean session without unrelated pending changes and turn off client autocommit for the DML tests.

Create the trigger for all three events

The first IF statement contains shared INSERT and UPDATE validation. The second IF statement handles the UPDATE-only price comparison or the DELETE history insert. INSERT needs no additional branch because the shared block already performs its work. This organization implements the same event-selection idea as the diagram without duplicating the common validation.

CREATE OR REPLACE TRIGGER product_demo_biud
BEFORE INSERT OR UPDATE OR DELETE ON product_trigger_demo
FOR EACH ROW
BEGIN
    IF INSERTING OR UPDATING THEN
        IF :NEW.sale_price IS NOT NULL
           AND :NEW.store_cost IS NOT NULL
           AND :NEW.sale_price < :NEW.store_cost THEN
            RAISE_APPLICATION_ERROR(
                -20001, 'Sale price must not be below store cost.');
        END IF;
    END IF;

    IF UPDATING THEN
        IF :OLD.sale_price IS NOT NULL
           AND :NEW.sale_price IS NOT NULL
           AND :NEW.sale_price < :OLD.sale_price THEN
            RAISE_APPLICATION_ERROR(
                -20002, 'This example does not allow price reductions.');
        END IF;
    ELSIF DELETING THEN
        INSERT INTO product_delete_demo
            (product_id, store_cost, sale_price, deleted_at)
        VALUES
            (:OLD.product_id, :OLD.store_cost,
             :OLD.sale_price, SYSTIMESTAMP);
    END IF;
END;
/

The declaration selects BEFORE timing because the example validates proposed changes. The name PRODUCT_DEMO_BIUD is a naming choice, not an Oracle keyword. No DECLARE section is needed because this body declares no local variables or named exceptions. The slash on its own line submits the PL/SQL unit in SQL*Plus, SQLcl, or a compatible script mode; it is not part of the trigger body.

Each rejection supplies a specific application error. If both validations fail, ORA-20001 is returned first because the cost comparison appears first. There is no catch-all handler hiding unexpected failures. A problem inserting history, for example, should propagate instead of being silently ignored or incorrectly reported as a price reduction.

Before running any DML, inspect the stored unit's compilation diagnostics:

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

Resolve any compilation errors before proceeding. USER_ERRORS can also contain compiler warnings when enabled, so read the diagnostic text rather than treating every entry as the same problem. A successful submission message alone should not substitute for checking the trigger's validity when creation reports compilation problems.

Establish a reversible test baseline

Run the following statements after the DDL has completed. The savepoint comes before the test inserts, which lets you remove all their transactional effects at the end. A newly created, empty pair of practice tables is assumed. These product identifiers are lab data, not references to particular rows in the Pet Store installation.

SAVEPOINT lesson6_start;

INSERT INTO product_trigger_demo (product_id, store_cost, sale_price)
VALUES (901, 10, 15);

INSERT INTO product_trigger_demo (product_id, store_cost, sale_price)
VALUES (902, 8, 12);

UPDATE product_trigger_demo
SET sale_price = 16
WHERE product_id = 901;

The expected state is product 901 with cost 10 and price 16, and product 902 with cost 8 and price 12. The INSERTs pass shared validation; the UPDATE passes both checks because the new price exceeds cost and increases the old price. These changes are still pending in the current transaction.

Verify that rejected statements leave the rows intact

Execute each deliberately failing statement below separately. Inspect its error before continuing, and use a client configuration that keeps the session available after an expected SQL error. A script setting that exits on the first error can prevent the later checks and rollback from running.

UPDATE product_trigger_demo
SET sale_price = 14
WHERE product_id = 901;

UPDATE product_trigger_demo
SET store_cost = 17
WHERE product_id = 901;

INSERT INTO product_trigger_demo (product_id, store_cost, sale_price)
VALUES (903, 10, 9);
Expected results for the three rejection tests
AttemptExpected errorReason
Reduce product 901's price to 14ORA-20002The price falls from 16, although it remains above cost.
Increase product 901's cost to 17ORA-20001The existing price of 16 would be below the new cost.
Insert product 903 with cost 10 and price 9ORA-20001The proposed price is below cost.

After these attempts, product 901 should still have cost 10 and price 16, product 902 should be unchanged, and product 903 should be absent. Query the practice table to confirm those values instead of relying only on an error message. The earlier successful INSERTs and UPDATE remain pending; a rejected statement does not automatically erase all earlier work in the transaction.

This distinction becomes especially important for a multirow statement. If one affected row violates the rule, the statement's changes are rolled back, including changes it made to other rows before the error. Oracle does not promise the row-processing order, so a test should compare the complete before-and-after result rather than depend on a particular row being processed first. See exception handling in triggers.

For such a test, first record every targeted product identifier, cost, and price. Choose a single UPDATE whose proposed values satisfy the rules for some rows and violate them for another, then compare all targeted rows with the recorded baseline after the rejection. Keep earlier setup statements outside that failing statement so you can also verify that they remain pending. This distinguishes statement atomicity from the final transaction decision made by the caller.

Test DELETE history and rollback together

Product 902 remains available for the DELETE test. Add a second savepoint so you can reverse that deletion while retaining the initial test rows. The history query intentionally selects stored amounts rather than predicting the exact timestamp produced on your system.

SAVEPOINT before_delete;

DELETE FROM product_trigger_demo WHERE product_id = 902;

SELECT product_id, store_cost, sale_price
FROM product_delete_demo
WHERE product_id = 902;

ROLLBACK TO before_delete;

SELECT product_id, store_cost, sale_price
FROM product_trigger_demo
WHERE product_id = 902;

SELECT COUNT(*) AS history_rows
FROM product_delete_demo
WHERE product_id = 902;

ROLLBACK TO lesson6_start;

Immediately after DELETE, the history table should contain product 902 with cost 8 and price 12. Rolling back to BEFORE_DELETE restores its source row and removes the history insert. The history count should then be zero in this fresh lab. The final rollback to LESSON6_START removes the earlier baseline inserts and update as well.

The tables and trigger remain because the final rollback reverses test DML, not the preceding object definitions. This makes it possible to repeat the transactional tests without recreating the trigger. If you later remove practice objects, do so deliberately after completing the rollback and confirming that those objects belong to this lab.

Choose transaction boundaries deliberately

The history insert is part of the transaction that performs the deletion. A failure or rollback must not leave this ordinary history row claiming a deletion that never persisted. An AFTER trigger can be a suitable design for recording completed row operations, but AFTER still does not mean that the application has committed its transaction.

Do not add COMMIT or ROLLBACK to this trigger or hide transaction control in a procedure it calls. Those operations belong to the caller's transaction design. Oracle's trigger restrictions also explain the mutating-table restriction: a simple row trigger should not query or modify its own changing table. This example uses pseudorecord fields and writes to a separate table.

An autonomous transaction is independent of the main transaction. It can persist a separately committed log even if the original change rolls back, but such a log might describe an attempted operation rather than a successful committed change. That is a different requirement. Do not make the validation trigger autonomous merely to bypass transaction-control restrictions.

Check edge cases and decide what belongs in a trigger

The main tests establish the normal paths, but a complete review should challenge the chosen rules. Test the following cases separately, starting from a known baseline and reversing each case before the next. Distinguish a statement that successfully changes a row from one that matches no rows.

For a production same-row price-versus-cost rule, normally prefer a CHECK constraint such as CHECK (sale_price >= store_cost). A CHECK condition can be UNKNOWN because of NULL and still pass, so required amounts need separate NOT NULL constraints. A CHECK also does not supply the custom application-error message. The old-to-new price transition is a separate requirement that cannot be expressed by this same-row comparison alone. Consult Oracle's constraint reference.

Before consolidating existing triggers, inventory their events, timing, enabled state, dependencies, and business rules. CREATE OR REPLACE replaces the named trigger; creating PRODUCT_DEMO_BIUD does not remove other differently named triggers. Leave the course triggers intact while working in these isolated tables. In a real migration, plan how the superseded triggers will be retired so their logic does not run alongside its replacement.

Combining related events can reduce duplicated code, but it does not guarantee better performance or justify a large body containing unrelated responsibilities. Keep event-specific branches easy to inspect. If shared logic grows, a suitably designed stored subprogram can centralize it while the trigger remains a small entry point.

Creating Trigger Combination - Exercise

Apply the same process in the Trigger Combination exercise: identify the shared rule, choose the event predicates, use the appropriate OLD and NEW fields, and specify both successful and rejected test cases. Explain what rollback should do before running the tests. The next lesson concludes the module.


SEMrush Software 6 SEMrush Banner 6