Sub topic 7
Validating Data and Filling Derived Columns in BEFORE Triggers
This chapter assumes you can write basic PL/SQL blocks, know the difference between a statement-level and a row-level trigger, and have seen :OLD and :NEW in earlier chapters. Here you will use BEFORE row triggers for two jobs: rejecting bad data and filling in columns the caller did not supply.
Why BEFORE Row Triggers Fit This Job
A BEFORE row trigger fires once for each affected row, before Oracle writes that row. At that point :NEW is still a writable record. Anything you assign to :NEW.column is what gets stored. An AFTER row trigger cannot do this. In an AFTER trigger, assigning to :NEW raises a compilation error, because the row is already written.
This gives BEFORE row triggers two natural uses:
- Validation: inspect
:NEWand raise an error to reject the statement. - Derived values: compute or default a column and assign it to
:NEW.
The order matters. Your trigger runs before constraint checking. A value you set in the trigger, such as a NOT NULL column's default, can satisfy the constraint. Oracle also checks constraints against the final :NEW values, not the values the caller typed.
Filling Derived Columns
The first example assigns a primary key from a sequence and stamps the creation time.
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;
/Three details are worth noting:
- The
IF :NEW.employee_id IS NULLtest lets callers supply their own key, for example during a data load. The trigger fills the key only when it is missing. created_atis assigned without a test. The trigger overwrites any value the caller sends, so the column cannot be forged.- In
:NEW.employee_id := employees_seq.NEXTVAL, the sequence is used directly in PL/SQL. Oracle 11g and later allow this. Earlier versions neededSELECT employees_seq.NEXTVAL INTO ... FROM dual.
Because the trigger fires for each row, a multirow INSERT ... SELECT gets a distinct key and timestamp assignment per row.
The trigger fires on every insert path: SQL*Plus, application code, loader tools. A default value in the table definition, or an identity column, is simpler for plain defaults. Use a trigger when the value needs logic, or when you must override what the caller sent.
Validating Data
Constraints such as CHECK, NOT NULL and foreign keys should be your first choice for validation. They are declarative, the optimizer can use them, and they need no code. A trigger is the right tool when the rule cannot be written as a constraint, for example when it compares old and new values, uses a function a CHECK constraint does not allow, or depends on the session.
The second example blocks salary decreases.
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;
/A CHECK constraint cannot express this rule, because a constraint sees only the new row. The trigger can compare :OLD and :NEW.
The WHEN clause refers to NEW and OLD without a colon. Inside the PL/SQL body you write :NEW and :OLD with a colon. Mixing the two up is a common compile error.
Raising Errors Well
RAISE_APPLICATION_ERROR(error_number, message) accepts numbers from -20000 to -20999. When it runs inside a trigger:
- The current DML statement is rolled back. Rows already changed by that same statement are undone.
- Work done earlier in the transaction by other statements stays pending. The caller decides whether to commit or roll back.
- The caller receives
ORA-20001: Salary cannot be decreased, followed by anORA-06512line naming the trigger.
Write messages that tell the user what to fix. Include the offending value when it helps, as in the next example.
CREATE OR REPLACE TRIGGER employees_val_bi
BEFORE INSERT OR UPDATE ON employees
FOR EACH ROW
BEGIN
IF :NEW.salary IS NOT NULL AND :NEW.salary < 0 THEN
RAISE_APPLICATION_ERROR(-20010,
'Salary must not be negative, got ' || :NEW.salary);
END IF;
IF :NEW.email IS NOT NULL THEN
:NEW.email := LOWER(TRIM(:NEW.email));
END IF;
END employees_val_bi;
/This trigger mixes both jobs. It rejects a negative salary and normalizes the email address. Normalizing before validating or storing keeps data consistent, so lookups by email do not depend on the case the caller used.
Handling NULL Correctly
Most validation bugs in triggers come from NULL. In PL/SQL, any comparison with NULL yields NULL, which IF treats as not true.
-- Bug: when :NEW.salary is NULL, the condition is not TRUE,
-- so the NULL is silently accepted.
IF :NEW.salary < 0 THEN
RAISE_APPLICATION_ERROR(-20010, 'Negative salary');
END IF;That behavior is sometimes what you want and sometimes not. Decide deliberately:
- If NULL is allowed, the plain comparison already passes it through.
- If NULL is forbidden, test for it explicitly with
IS NULL, or add aNOT NULLconstraint.
The same rule affects the WHEN (NEW.salary < OLD.salary) clause from earlier. If either value is NULL, the condition is not true and the trigger does not fire. A raise from NULL to a value, or a drop from a value to NULL, is therefore not blocked. Add OR NEW.salary IS NULL if that case matters to you.
Behavior on UPDATE
On an UPDATE, :NEW starts as a copy of the old row with your SET changes applied. Two consequences follow:
- You can assign to
:NEWcolumns the statement did not mention, such as alast_modifiedcolumn. The assignment is stored. - You cannot assign to
:OLD. It is read-only.
The next trigger maintains an update timestamp and prevents the key from changing.
CREATE OR REPLACE TRIGGER employees_bu
BEFORE UPDATE ON employees
FOR EACH ROW
BEGIN
IF :NEW.employee_id != :OLD.employee_id THEN
RAISE_APPLICATION_ERROR(-20011, 'employee_id cannot be changed');
END IF;
:NEW.updated_at := SYSTIMESTAMP;
END employees_bu;
/On INSERT, :OLD fields are all NULL. On DELETE, :NEW fields are all NULL. If one trigger handles several events, use the INSERTING, UPDATING and DELETING predicates to guard code that depends on which record is valid.
Limits and Gotchas
- Do not query or modify the triggering table in a row trigger. A
SELECTfromemployeesinside a row trigger onemployeesraises ORA-04091, the mutating table error. A later chapter covers it. Validate using:NEWand:OLD, or other tables. - Do not commit. A trigger runs inside the caller's transaction.
COMMITandROLLBACKare not allowed there. - Rows can be restarted. Oracle may re-run a BEFORE row trigger for the same row, for example to keep a statement read-consistent after a concurrent change. Code with side effects outside the database, such as sending mail, can then run twice. Keep BEFORE triggers free of such side effects.
- Sequence gaps. If a later error rolls back the insert, the sequence value is still used. Do not rely on gap-free numbers.
- Bulk loads. Direct-path loads can bypass triggers or require them to be disabled. Do not treat a trigger as the only barrier for data integrity if such loads happen. Constraints remain enforced.
- Keep it fast. The body runs once per row, so a slow trigger multiplies by the row count.
Choosing Between a Constraint, a Default and a Trigger
| Need | Best tool |
|---|---|
| Value must be non-null, unique or in a range | Constraint |
| Simple default when the column is omitted | `DEFAULT` clause or identity column |
| Compare old and new values | BEFORE UPDATE row trigger |
| Overwrite what the caller sent | BEFORE row trigger |
| Rule spans several rows of the same table | Compound trigger (later chapter) |
Exercise
A table has a column status. You want every inserted row to store status in upper case, and you want to reject any update that changes hire_date. Which trigger timing and level do you use, and why can a CHECK constraint not enforce the hire_date rule?
Show answer
Use a BEFORE INSERT OR UPDATE row trigger (FOR EACH ROW). It must be BEFORE because assigning :NEW.status := UPPER(:NEW.status) is only allowed before the row is stored, and it must be a row trigger because :NEW and :OLD exist only at row level. A CHECK constraint sees only the new row values, so it cannot compare them with the old hire_date. The trigger can test UPDATING AND :NEW.hire_date != :OLD.hire_date and call RAISEAPPLICATIONERROR.
Exercise
The trigger BEFORE UPDATE OF salary ... WHEN (NEW.salary < OLD.salary) is in place. A user runs UPDATE employees SET salary = NULL WHERE employee_id = 100, and the row is updated. Why, and how would you change the WHEN clause to block it?
Show answer
The comparison NULL < OLD.salary evaluates to NULL, which is not true, so the trigger does not fire. Change the clause to WHEN (NEW.salary < OLD.salary OR NEW.salary IS NULL), or add a NOT NULL constraint on the column.