Sub topic 3
Writing Your First Trigger with CREATE OR REPLACE TRIGGER
This chapter assumes you can write basic SQL DML and PL/SQL blocks (variables, IF, exceptions). It also assumes you know what a sequence is and how COMMIT and ROLLBACK work. The previous chapters explained what a trigger is and how timing and level combine. Here you write one, read its syntax piece by piece, and learn how to find and fix compile errors.
Setup
The examples use a small employees table and a sequence. Run this once in SQL*Plus, SQLcl, or SQL Developer.
CREATE SEQUENCE employees_seq START WITH 1 INCREMENT BY 1;
CREATE TABLE employees (
employee_id NUMBER PRIMARY KEY,
last_name VARCHAR2(50) NOT NULL,
department_id NUMBER,
salary NUMBER(10,2),
created_at TIMESTAMP
);The first trigger
This trigger fills in the primary key and a creation timestamp whenever a row is inserted.
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;
:NEW.created_at := SYSTIMESTAMP;
END employees_bi;
/Test it by inserting a row without an id or a timestamp:
INSERT INTO employees (last_name, department_id, salary)
VALUES ('Khan', 10, 5000);
SELECT employee_id, last_name, created_at FROM employees;
ROLLBACK;The query returns one row with employee_id set to the next sequence value (1 on a fresh sequence) and created_at set to the time of the insert. The trigger ran inside the INSERT, before the row was stored. The calling statement never mentioned either column.
Anatomy of the statement
The full statement has this shape. Square brackets mark optional parts.
CREATE [OR REPLACE] TRIGGER [schema.]trigger_name
{BEFORE | AFTER | INSTEAD OF}
{INSERT | UPDATE [OF column_list] | DELETE} [OR ...]
ON {table | view}
[REFERENCING OLD AS old_name NEW AS new_name]
[FOR EACH ROW]
[FOLLOWS other_trigger]
[ENABLE | DISABLE]
[WHEN (condition)]
[DECLARE
declarations]
BEGIN
statements
[EXCEPTION
handlers]
END [trigger_name];The order of the clauses matters. Oracle rejects the statement if, for example, WHEN comes before FOR EACH ROW. The table below maps each part to the first trigger.
| Part | In `employees_bi` | Meaning |
|---|---|---|
| `OR REPLACE` | present | Replaces an existing trigger of the same name, so you do not need to drop it first |
| Timing | `BEFORE` | Fires before the row is written |
| Event | `INSERT` | The DML operation that fires the trigger |
| `ON` | `employees` | The table (or view, for `INSTEAD OF`) that owns the trigger |
| `FOR EACH ROW` | present | Makes it a row-level trigger. Without it, the trigger is statement-level and fires once per statement |
| Body | `BEGIN ... END` | An ordinary PL/SQL block |
The trailing / is not part of the trigger. It is a SQL*Plus and SQLcl command that sends the buffered PL/SQL block to the database. You need it after every trigger, because the body contains semicolons.
What the body can do
The body is a PL/SQL block. You can declare variables, call stored procedures, query other tables, and handle exceptions. Three things are different from a normal block:
- Row-level triggers can read and, in
BEFOREtriggers, assign:NEWand:OLDvalues. The next chapter covers these. - The trigger runs in the transaction of the statement that fired it. It cannot issue
COMMITorROLLBACK, and it can useRAISE_APPLICATION_ERRORto make the whole statement fail. - A trigger has no parameters and returns nothing. Its only inputs are the row values, the session context, and the database state.
Here is a statement-level trigger, which omits FOR EACH ROW. It has no :NEW or :OLD, because it is not tied to one row.
CREATE OR REPLACE TRIGGER employees_no_weekend_dml
BEFORE INSERT OR UPDATE OR DELETE ON employees
BEGIN
IF TO_CHAR(SYSDATE, 'DY', 'NLS_DATE_LANGUAGE=ENGLISH') IN ('SAT', 'SUN') THEN
RAISE_APPLICATION_ERROR(-20010, 'Changes to employees are not allowed on weekends');
END IF;
END employees_no_weekend_dml;
/This trigger fires once per statement, even if the statement touches thousands of rows, and even if it touches none. On a Saturday or Sunday it would block every change to employees, so drop it after you try it:
DROP TRIGGER employees_no_weekend_dml;The NLS_DATE_LANGUAGE argument keeps the day abbreviation in English regardless of the session language. Without it, the test would silently never match in a French or German session.
Required privileges
To create a trigger in your own schema you need the CREATE TRIGGER privilege, and you must own the table or have the ALTER privilege on it. To create a trigger in another schema, you need CREATE ANY TRIGGER. A trigger runs with the privileges of its owner, not of the user who ran the DML. Roles do not count here, so the owner needs direct grants on any other objects the body touches.
Compile errors
A trigger is compiled when you create it. If the body has an error, Oracle still stores the trigger and reports this:
Warning: Trigger created with compilation errors.The trigger exists but has status INVALID. This matters more than it does for a procedure. Because the trigger belongs to the table, DML that would fire an invalid trigger fails with ORA-04098: trigger 'HR.EMPLOYEES_BI' is invalid and failed re-validation. A typo in a trigger can therefore stop all inserts into the table.
To see the errors, use SHOW ERRORS right after the failed statement, or query the data dictionary later:
SHOW ERRORS TRIGGER employees_bi
SELECT line, position, text
FROM user_errors
WHERE name = 'EMPLOYEES_BI'
AND type = 'TRIGGER'
ORDER BY sequence;A common first error is the line PLS-00049: bad bind variable 'NEW.CREATED_AT'. It usually means the trigger is on a table that has no column of that name, or that FOR EACH ROW is missing. Without FOR EACH ROW, :NEW and :OLD are not available at all.
Rules to remember
- Assign to
:NEWonly inBEFORErow triggers. In anAFTERrow trigger,:NEWis read-only, and an assignment fails to compile withORA-04084: cannot change NEW values for this trigger type. - Name triggers by table and type, for example
employees_bi(before insert) oremployees_aud(audit). A consistent suffix makesUSER_TRIGGERSeasy to read. - Keep the body short. Put long logic in a stored procedure and call it from the trigger, so you can test it separately.
CREATE OR REPLACEswaps the definition in place. If the new text has errors, you still get an invalid trigger, so checkUSER_ERRORSafter each change.- A trigger can be created on a table that already holds data. It does not fire for existing rows. It fires only for DML run after it is created.
Exercise
You run CREATE OR REPLACE TRIGGER on employees with an AFTER INSERT row trigger whose body contains the line :NEW.createdat := SYSTIMESTAMP; and then insert a row. What happens, and how do you fix the trigger so that createdat is filled in?
Show answer
The trigger fails to compile, with ORA-04084 "cannot change NEW values for this trigger type", because an AFTER row trigger cannot assign to :NEW. Oracle stores the trigger as invalid, and inserts into employees then fail with ORA-04098 until it is fixed. Change the timing to BEFORE INSERT (keeping FOR EACH ROW) so the assignment happens before the row is stored, then recreate the trigger and check USER_ERRORS to confirm it compiled.
Exercise
A colleague writes a trigger that ends with END; but forgets the line containing only /. What do you see in SQL*Plus, and why?
Show answer
SQLPlus does not execute the block. It waits for more input or treats the next lines as part of the same buffer, so no trigger is created. The / line is the SQLPlus command that sends the PL/SQL block to the database. Because the trigger body contains semicolons, SQL*Plus cannot use the semicolon to tell where the statement ends.