Sub topic 2
Timing and Level: Choosing the Kind of Trigger
This chapter assumes you can write basic SQL DML and PL/SQL blocks, and that you understand COMMIT and ROLLBACK. Every trigger you write has two properties that decide when it runs and what it can do: its timing and its level. This chapter explains both and shows how to pick them.
The Two Choices
Timing says when the trigger fires relative to the triggering event:
BEFOREfires before the change is applied.AFTERfires after the change is applied.INSTEAD OFfires in place of the change. It is used only on views.
Level says how often the trigger fires for one DML statement:
- A statement-level trigger fires once per statement, however many rows the statement touches, including zero.
- A row-level trigger fires once per affected row. You request it with
FOR EACH ROW.
If you leave out FOR EACH ROW, you get a statement-level trigger. Forgetting the clause is a common mistake, because the trigger compiles but never behaves as a per-row trigger.
The Four Timing Points
Combining timing and level for a table gives four timing points around one DML statement.
You can see this order by creating one trigger for each timing point on a small table. The DBMS_OUTPUT calls print which trigger ran.
CREATE TABLE trg_demo (
id NUMBER PRIMARY KEY,
val VARCHAR2(20)
);
CREATE OR REPLACE TRIGGER trg_demo_bs
BEFORE UPDATE ON trg_demo
BEGIN
DBMS_OUTPUT.PUT_LINE('BEFORE STATEMENT');
END trg_demo_bs;
/
CREATE OR REPLACE TRIGGER trg_demo_br
BEFORE UPDATE ON trg_demo
FOR EACH ROW
BEGIN
DBMS_OUTPUT.PUT_LINE('BEFORE EACH ROW, id ' || :OLD.id);
END trg_demo_br;
/
CREATE OR REPLACE TRIGGER trg_demo_ar
AFTER UPDATE ON trg_demo
FOR EACH ROW
BEGIN
DBMS_OUTPUT.PUT_LINE('AFTER EACH ROW, id ' || :OLD.id);
END trg_demo_ar;
/
CREATE OR REPLACE TRIGGER trg_demo_as
AFTER UPDATE ON trg_demo
BEGIN
DBMS_OUTPUT.PUT_LINE('AFTER STATEMENT');
END trg_demo_as;
/Now insert two rows and update both:
SET SERVEROUTPUT ON
INSERT INTO trg_demo VALUES (1, 'a');
INSERT INTO trg_demo VALUES (2, 'b');
UPDATE trg_demo SET val = 'x';The output is:
BEFORE STATEMENT
BEFORE EACH ROW, id 1
AFTER EACH ROW, id 1
BEFORE EACH ROW, id 2
AFTER EACH ROW, id 2
AFTER STATEMENTNow run an update that matches no rows:
UPDATE trg_demo SET val = 'y' WHERE id = 999;Only the two statement-level triggers print. The statement ran, so statement triggers fire. No row was affected, so row triggers do not.
What Each Kind Can Do
The kinds differ in what they are allowed to touch.
| Kind | Fires | Can read `:OLD` and `:NEW` | Can assign to `:NEW` | Typical use |
|---|---|---|---|---|
| BEFORE statement | Once, before any row changes | No | No | Check who may run the statement, or the time of day |
| BEFORE row | Per row, before it is stored | Yes | Yes | Validate values, fill derived columns |
| AFTER row | Per row, after it is stored | Yes | No | Auditing, copying changes elsewhere |
| AFTER statement | Once, after all rows change | No | No | Summary work, logging that a statement ran |
| INSTEAD OF (row) | Per row, replacing the view DML | Yes | Not meaningful | Make a view modifiable |
Two rules in this table cause most beginner errors.
:OLDand:NEWexist only in row-level triggers. A statement-level trigger that mentions:NEWfails to compile.- Only a BEFORE row trigger may assign to
:NEW. The row is already stored when an AFTER row trigger runs. Assigning to:NEWthere fails with ORA-04084.
Choosing Between BEFORE and AFTER
Ask what the trigger needs to do.
Use a BEFORE row trigger when you want to change or reject the incoming row. The row has not been written yet, so you can set a default or normalize a value. You can also raise an error and skip the write cost. Rejecting early avoids wasted work, such as index maintenance and foreign key checks for a row you are about to discard.
Use an AFTER row trigger when your action depends on the row being stored. An audit record is the usual case. You want to log only changes that passed all constraint checks. Constraints are checked as part of the statement, so a row that violates one never reaches the AFTER row trigger for that row's final state.
Use a statement-level trigger when the rule concerns the statement as a whole and not the individual rows. Examples are blocking DML outside a maintenance window and recording that a bulk load happened.
CREATE OR REPLACE TRIGGER trg_demo_window
BEFORE INSERT OR UPDATE OR DELETE ON trg_demo
BEGIN
IF TO_NUMBER(TO_CHAR(SYSDATE, 'HH24')) BETWEEN 2 AND 3 THEN
RAISE_APPLICATION_ERROR(-20010, 'trg_demo is read-only during the nightly batch');
END IF;
END trg_demo_window;
/This trigger does not need row values, so a statement-level trigger is cheaper. It runs once, not once per row.
Cost of Row Triggers
A row trigger runs PL/SQL code for every row. For a statement that changes 100,000 rows, that is 100,000 executions, each involving a switch between the SQL engine and the PL/SQL engine. A slow trigger body makes bulk DML slow. When the logic can be written once per statement, prefer a statement-level trigger. When you need row data but also a final check over the whole table, a compound trigger (a later chapter) combines both.
Triggers on Views
DML on a view is a special case. A view has no storage of its own, so BEFORE and AFTER row triggers make no sense on it. For a view whose DML Oracle cannot translate to the base tables, such as a join view, you write an INSTEAD OF trigger. Its code replaces the DML and performs the real changes on the base tables itself. INSTEAD OF triggers are always row-level. A later chapter covers them in detail.
Several Events and Multiple Triggers
One trigger may name several events, for example BEFORE INSERT OR UPDATE OR DELETE. The timing and level apply to all of them. A table may also have many triggers for the same timing point. If you have more than one, their relative order is not defined unless you use FOLLOWS, which a later chapter covers. If two triggers of the same kind depend on each other's results, define the order explicitly.
MERGE and Multiple Events
A MERGE statement does not have its own trigger event. It fires the INSERT triggers for the rows it inserts and the UPDATE triggers for the rows it updates. Statement-level triggers for both events can fire. Test your triggers with MERGE if your application uses it, because the combined firing can surprise you.
Decision Guide
Work through these questions in order.
- Is the target a view that needs DML support? Use
INSTEAD OF. - Do you need to read or change individual row values? Use a row-level trigger. Otherwise use statement-level.
- Must you modify the incoming row or reject it before it is stored? Use BEFORE.
- Must the action depend on the row having been stored? Use AFTER.
- Does the rule need a query of the same table? Plan for a compound trigger, because plain row triggers cannot do this safely.
Exercises
Exercise
You need to set :NEW.created_at := SYSTIMESTAMP for every inserted row. Which timing and level do you choose, and why?
Show answer
BEFORE INSERT with FOR EACH ROW. Only a BEFORE row trigger can assign to :NEW, and the value must be set before the row is stored. An AFTER trigger would fail with ORA-04084, and a statement-level trigger cannot access :NEW.
Exercise
You run UPDATE trg_demo SET val = 'z' WHERE id = 12345; and no row has that id. Which of the four triggers from this chapter print output, and which do not?
Show answer
BEFORE STATEMENT and AFTER STATEMENT print, because the statement ran. The BEFORE EACH ROW and AFTER EACH ROW triggers do not print, because no row was affected.
Exercise
A colleague writes CREATE OR REPLACE TRIGGER t AFTER UPDATE ON trg_demo BEGIN DBMS_OUTPUT.PUT_LINE(:OLD.val); END; and the trigger fails to compile. What is wrong, and how do you fix it?
Show answer
The trigger has no FOR EACH ROW clause, so it is a statement-level trigger, and :OLD is not available there. Add FOR EACH ROW after the ON clause to make it a row-level trigger.