Sub topic 1
What Is a Database Trigger?
Prerequisites
This chapter assumes you can write SELECT, INSERT, UPDATE, and DELETE statements, read a simple PL/SQL block with variables and IF statements, and explain COMMIT and ROLLBACK. You should also know how tables, views, and sequences work in Oracle.
What a Database Trigger Is
A trigger is a named PL/SQL block that the database runs automatically when a change happens to a table or view, such as an INSERT, UPDATE, or DELETE. Applications do not call it directly. Use a trigger when a rule must hold no matter which program changes the data, such as filling an audit column or enforcing a rule that a CHECK constraint cannot express. Constraints are simpler and cheaper, so prefer them when they fit.
Timing and Level: Choosing the Kind of Trigger
Two choices define each trigger. Timing sets when it runs: BEFORE the change, AFTER the change, or INSTEAD OF a change to a view. Level sets how often it runs: once per statement (the default) or once per affected row when you add FOR EACH ROW.
| Timing | Level | Typical use |
|---|---|---|
| BEFORE | FOR EACH ROW | Validate values or set derived columns |
| AFTER | FOR EACH ROW | Write audit records |
| INSTEAD OF | FOR EACH ROW | Make a complex view modifiable |
| BEFORE or AFTER | Statement | Check a rule once per statement |
Writing Your First Trigger with CREATE OR REPLACE TRIGGER
Use CREATE OR REPLACE TRIGGER so you can rerun the script after changes. The slash on its own line ends the block in SQL*Plus or SQLcl.
CREATE OR REPLACE TRIGGER employees_bi
BEFORE INSERT ON employees
FOR EACH ROW
BEGIN
IF :NEW.employee_id IS NULL THEN
:NEW.employee_id := employees_seq.NEXTVAL;
END IF;
END employees_bi;
/This trigger fills the key from a sequence only when the caller leaves it empty.
Reading and Changing Row Values with :OLD and :NEW
In a row-level trigger, :NEW holds the column values after the change, and :OLD holds the values before it. For an INSERT, :OLD is empty. For a DELETE, :NEW is empty. In a BEFORE row trigger, you can assign to :NEW to change the row before it is stored. Use the colon prefix in the body. In a WHEN clause, omit it.
CREATE OR REPLACE TRIGGER employees_salary_chk
BEFORE UPDATE OF salary ON employees
FOR EACH ROW
WHEN (NEW.salary < OLD.salary)
BEGIN
RAISE_APPLICATION_ERROR(-20001, 'Salary cannot be decreased');
END employees_salary_chk;
/Exercise
Why does employeesbi check whether :NEW.employeeid IS NULL before it assigns a value?
Show answer
It fills the key only when the caller did not supply one. If the caller supplies an id, the trigger keeps that value.