| Lesson 3 | Oracle triggers and stored procedures |
| Objective | Distinguish between a trigger and a procedure in Oracle 26ai. |
A stored procedure provides a named operation that a caller invokes. A database trigger associates code with a database event, so Oracle invokes the enabled trigger when that event and its conditions apply. Both can contain PL/SQL, execute SQL, and call other subprograms. Their different activation mechanisms determine how an application uses and tests them.
For example, an application might call a procedure to change an item's price. The procedure executes an UPDATE, and that statement can automatically fire a trigger that records when the row was updated. The procedure and trigger cooperate within the same transaction. Returning from the procedure does not, by itself, commit either change.
This lesson compares stored procedures with ordinary DML triggers in Oracle AI Database 26ai. These principles also apply to earlier Oracle releases. The example separates an explicit price-change operation from automatic timestamp maintenance, then uses a savepoint to demonstrate their shared transaction.
| Characteristic | DML trigger | Stored procedure |
|---|---|---|
| Activation | Oracle invokes it for its configured event and conditions. | A client, program, job, or another database unit invokes it. |
| Inputs | No application-supplied argument list; row triggers receive event context through OLD and NEW. | Can declare IN, OUT, and IN OUT parameters. |
| Results | No function return value or OUT interface; permitted changes and exceptions affect the triggering operation. | Can supply OUT or IN OUT results; it is not a function expression. |
| Transaction | Normally shares the triggering statement's transaction. | Normally shares the caller's transaction. |
| Reuse | Event-specific code can delegate shared work to subprograms. | The same interface can serve several callers. |
| Testing | Perform triggering operations and inspect their effects and errors. | Invoke it with selected arguments and inspect outputs, data, and errors. |
The transaction comparison assumes nonautonomous execution. Explicitly autonomous routines are an advanced exception, discussed below. A procedure's independent name and interface do not give it a separate transaction.
An application can invoke a stored procedure through its database driver. PL/SQL can invoke it by name as a statement, and Oracle Scheduler can execute an appropriate stored procedure as a scheduled job. A trigger can also call a procedure. Consequently, saying that procedures cannot execute automatically is misleading: their execution requires a call, but software can make that call without a person intervening.
SQL CALL can invoke a stored routine. This does not make a procedure a value-producing expression that can be placed in a SELECT list. In SQL*Plus-style clients, EXECUTE, often abbreviated EXEC, is a client command for executing PL/SQL. Distinguish that convenience command from Oracle SQL syntax and from a procedure call inside a PL/SQL block.
A trigger has no comparable application-call interface. You cause an eligible DML trigger to fire by issuing its triggering operation. Direct SQL and SQL inside a procedure are both capable of firing it. Disabling a trigger changes this behavior, so a valid compiled object is not necessarily an enabled one.
An IN parameter supplies input, an OUT parameter supplies a result to the caller, and an IN OUT parameter supports both directions. The caller provides compatible arguments. A procedure may use a bare RETURN; to exit early, but it does not return a function value through RETURN expression.
Row triggers instead use correlation pseudorecords such as :OLD and :NEW. Their fields describe the row involved in the triggering operation; they are not formal parameters supplied by an application. Which values are meaningful, and whether a field can be assigned, depends on the event and timing point. The example uses a permitted assignment to :NEW in a BEFORE row trigger.
Ordinary procedures share their caller's transaction. If a procedure performs several updates and returns successfully, those changes remain uncommitted unless some operation has explicitly or implicitly committed them. The caller can combine them with other work and then commit or roll back the transaction.
Where transaction control is allowed, a procedure's COMMIT commits the current transaction, including earlier uncommitted work in that transaction. It does not commit only the statements inside that procedure. A reusable business procedure commonly leaves transaction completion to its caller so that several related operations can succeed or fail together.
An ordinary DML trigger cannot issue transaction-control statements. Moving a COMMIT into a nonautonomous procedure called by that trigger does not avoid the restriction: the called routine executes in the trigger's context. Oracle documents this in Subprograms Invoked by Triggers.
An explicitly autonomous routine uses a separate transaction. Its committed changes can survive rollback of the main transaction, which makes its behavior materially different. Autonomous execution requires deliberate design; it is not the default behavior of a procedure and is not needed for the timestamp example.
Use a practice schema with unused object names. Creating these objects requires CREATE TABLE, CREATE PROCEDURE, CREATE TRIGGER, and sufficient tablespace quota. Finish the DDL setup before testing: Oracle DDL performs implicit commits. Use a dedicated connection without pending application work, turn client autocommit off, and enable DBMS_OUTPUT display if you want to see the printed row count.
Run the blocks in order using your client's script facility. The slash after a PL/SQL unit is a SQL*Plus-style script terminator; it is not part of the PL/SQL body submitted through a database API. The expected results below describe the example's behavior, not a captured execution transcript.
CREATE TABLE demo_tp_items (
item_id NUMBER PRIMARY KEY,
price NUMBER(10,2) NOT NULL CHECK (price >= 0),
changed_at TIMESTAMP WITH TIME ZONE
);
CREATE OR REPLACE TRIGGER demo_tp_stamp
BEFORE INSERT OR UPDATE ON demo_tp_items
FOR EACH ROW
BEGIN
:NEW.changed_at := SYSTIMESTAMP;
END;
/
The primary key identifies an item. Separate NOT NULL and CHECK constraints enforce a required, nonnegative price. Those rules belong in constraints rather than duplicate procedural checks. The trigger supplies the timestamp before each affected row is inserted or updated.
This trigger also runs for permitted direct DML that bypasses the procedure. It stamps qualifying updates even when the assigned price equals its previous value. The column therefore records an update event, not proof that the price changed. An insertion default alone would not maintain the timestamp on subsequent updates.
CREATE OR REPLACE PROCEDURE set_demo_tp_price (
p_item_id IN NUMBER,
p_price IN NUMBER,
p_rows OUT PLS_INTEGER
)
AUTHID DEFINER
AS
BEGIN
UPDATE demo_tp_items
SET price = p_price
WHERE item_id = p_item_id;
p_rows := SQL%ROWCOUNT;
END;
/
The procedure receives an item identifier and requested price. Its WHERE clause limits the update to that item, and the primary key means at most one row qualifies. The OUT parameter reports affected rows. Capture SQL%ROWCOUNT immediately after the relevant statement so subsequent SQL does not replace the result you intended to report.
A missing item produces zero affected rows under this interface. An UPDATE affecting no rows does not raise NO_DATA_FOUND. Applications can decide how to handle the zero result. For an existing item, a price violating the constraints raises an error instead of returning a successful count. The procedure deliberately contains no transaction-control statement.
If the application requires a missing identifier to be an error, define that policy explicitly and raise an appropriate application exception when the row count is zero. That would be a different procedure contract from this example. A NULL identifier also matches no row here. Document this behavior so callers can distinguish a successful one-row update from a request that completed without finding its target.
SELECT name, type, attribute, line, position, text
FROM user_errors
WHERE (name = 'SET_DEMO_TP_PRICE' AND type = 'PROCEDURE')
OR (name = 'DEMO_TP_STAMP' AND type = 'TRIGGER')
ORDER BY name, sequence;
Correct entries marked ERROR before testing and review any WARNING entries. When both objects compile without errors or recorded warnings, this query returns no diagnostics. Compilation confirms that Oracle accepts the definitions; it does not establish that every argument, privilege arrangement, and runtime dependency behaves correctly.
INSERT INTO demo_tp_items (item_id, price)
VALUES (1, 10);
SAVEPOINT before_price_change;
DECLARE
l_rows PLS_INTEGER;
BEGIN
set_demo_tp_price(
p_item_id => 1,
p_price => 12.50,
p_rows => l_rows
);
DBMS_OUTPUT.PUT_LINE('Rows updated: ' || l_rows);
END;
/
SELECT item_id, price, changed_at
FROM demo_tp_items
WHERE item_id = 1;
ROLLBACK TO before_price_change;
SELECT item_id, price, changed_at
FROM demo_tp_items
WHERE item_id = 1;
ROLLBACK;
The seed insert fires the trigger and assigns the initial timestamp. After the savepoint, the explicit procedure call updates the price and fires the trigger again. With DBMS_OUTPUT enabled, the printed message is Rows updated: 1. The first query shows price 12.50, although the client's numeric display may omit trailing zeros.
Rolling back to the savepoint restores price 10 and the timestamp stored before the procedure call. Returning from the procedure did not make either update permanent. Timestamp formatting depends on the client and session, and rapid operations need not produce visibly distinct displayed timestamps.
The final ROLLBACK removes the uncommitted seed row and ends the transaction. The table, procedure, and trigger remain because they were created during the earlier DDL setup. Do not insert a commit, DDL statement, or client autocommit between the savepoint and its rollback.
The diagram shows one successful INSERT statement affecting three rows, with one enabled trigger at each illustrated timing point. It illustrates a broader sequence than the example, which uses one row and one BEFORE row trigger. Oracle applies the relevant timing rules whether the statement comes from a procedure or directly from a client.
The row cycle repeats for each affected row. Do not interpret the diagram as all row-level BEFORE triggers running before any rows are inserted, or as a guarantee about which row is processed first. An AFTER STATEMENT trigger runs after its statement, not after the transaction commits. A transaction can contain many statements.
A compound DML trigger can organize related actions at several timing points. If multiple triggers share a timing point, do not rely on their creation order. Oracle's trigger ordering documentation explains supported ordering controls, including FOLLOWS where applicable.
A small trigger can pass individual row values to a reusable procedure or package subprogram. The subprogram can serve other callers too, provided its behavior is appropriate in their execution contexts. Conversely, a procedure's DML can fire triggers. Both directions are valid; document the dependencies so that an apparently simple call does not conceal unexpected writes.
Repeated row-trigger firings within one statement are different from cascading triggers. Cascading occurs when SQL issued by one trigger activates another trigger. Circular dependencies can produce recursion or repeated work. Calling a helper procedure does not remove trigger-context restrictions, including relevant transaction-control and mutating-table restrictions.
Table, view, schema, and database describe associated objects or event categories, not the row-versus-statement distinction. This module concentrates on table DML triggers. INSTEAD OF triggers on suitable views and schema or database event triggers have their own purposes and restrictions; they should not be treated as interchangeable timing options for every table operation.
The example explicitly uses AUTHID DEFINER. Privilege context and transaction context are separate: choosing definer's or invoker's rights does not make a transaction autonomous. Callers need the required execution privileges, and object dependencies need appropriate grants. An invoker's-rights routine called by a trigger uses the trigger-owner context described in Oracle's documentation; do not assume it automatically runs as the original application login.
Test missing identifiers, constraint violations, unchanged values, and rollback as well as the successful case. Test triggers against statements affecting several rows and against zero-row statements. Row-level work runs for affected rows; statement-level triggers can fire even when no rows qualify. A single-row demonstration does not establish multirow correctness.
For a repeatable test, establish the starting data, perform one operation, inspect the result, and restore the starting state. Check both the procedure's output and the table contents: a reported row count alone cannot establish that the timestamp behavior is correct. Use the same connection when checking uncommitted changes, since another session does not normally see them.
For ordinary DML triggers, an unhandled exception normally causes the triggering statement and its trigger effects to fail together, as described in Oracle's exception-handling guidance. This does not mean every earlier statement in the caller's transaction has been rolled back. The application still needs a clear error and transaction policy. Avoid a blanket exception handler that suppresses an error and reports success after required work has failed.
A helper procedure is not a separate execution environment that makes otherwise restricted trigger operations safe. For example, querying the table currently being modified from a row trigger can encounter the mutating-table restriction, even when the query is hidden in another routine. Redesign the data flow or use an appropriate compound-trigger approach when statement-wide information is required.
Performance depends on the SQL and work performed. A small per-row operation can become expensive across a large update. Measure the complete operation, including triggers fired by a procedure's SQL. Neither object type is inherently the faster choice, and compilation alone cannot reveal workload-dependent costs.
Keep deployment and execution separate when investigating unexpected behavior. Creating a procedure stores its definition; it does not run its business operation. Creating an enabled DML trigger prepares it for subsequent matching events; it does not replay earlier changes. Inspect the current definition, compilation diagnostics, enablement, and relevant privileges before attributing a missing effect to the application's calling syntax.
Use constraints for rules they can express and defaults for suitable insertion values. Use a procedure when callers need a named operation with defined inputs, outputs, and error behavior. Use a trigger when justified behavior must accompany qualifying database events across permitted access paths.
The example's timestamp does not preserve historical prices or replace a complete audit design. Similarly, a procedure interface does not prevent direct table changes unless privileges enforce that access policy. Define the requirement first, then choose the combination of declarative rules, callable routines, and event-driven behavior that satisfies it.
For further reading, see Oracle's subprogram parameter documentation, DML triggers, and autonomous transactions. The next lesson examines the special variables available when coding a trigger, including the OLD and NEW row context used here.