Sub topic 16
Best Practices and Common Pitfalls
This chapter assumes you know basic SQL, PL/SQL blocks, exceptions, transactions, tables, views, and sequences. It also assumes you understand row-level and statement-level triggers, :OLD and :NEW, compound triggers, and Oracle data dictionary views.
Triggers are useful when a rule must run for every session that changes a table. They are less suitable for ordinary application workflow. Before creating one, ask whether a constraint, generated column, stored procedure, or application service expresses the rule more clearly.
Keep Trigger Responsibilities Small
A trigger should perform one closely related task. Good examples include:
- Filling a creation timestamp.
- Rejecting an invalid change.
- Writing an audit row.
- Translating changes made to a complex view.
Avoid placing unrelated business processes in one trigger. Small triggers are easier to test and troubleshoot. Give them names that state the table, event, and purpose, such as employees_salary_chk.
Prefer declarative features when they fit. A CHECK constraint is usually clearer than a trigger for a simple value rule. A foreign key is safer than trigger code that checks whether a parent row exists.
Avoid Hidden Side Effects
A trigger runs implicitly. Code that inserts into employees may also update an audit table, call another trigger, and raise an exception. Document these effects and keep trigger chains short.
Do not commit or roll back inside an ordinary trigger. The triggering statement and the trigger share one transaction. If the statement fails, the trigger's changes normally roll back with it. An autonomous transaction can commit independently, but it creates a separate transaction and should be reserved for carefully designed cases such as emergency diagnostic logging.
Do not use an autonomous transaction to force audit data to remain after a business transaction rolls back unless that behavior is explicitly required. It can produce audit records for changes that never committed.
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;
/Handle Errors and Recursion Carefully
Raise specific errors with RAISE_APPLICATION_ERROR and document their meaning. Avoid catching WHEN OTHERS and ignoring SQLCODE or SQLERRM. Silent failure makes the original data change appear successful when a required action did not happen.
A trigger that modifies its own table, directly or through another trigger, can cause recursion or unexpected results. Check whether the operation can be replaced with a constraint or moved into a controlled stored procedure.
A row trigger that queries or changes the table currently being modified can raise ORA-04091, the mutating table error. Use a compound trigger to collect row information and query the table in its AFTER STATEMENT section.
Test and Monitor the Deployment
Test inserts, updates, deletes, multi-row statements, failed statements, and rollback behavior. A trigger that works for one row may expose problems when an update affects thousands of rows.
Keep trigger source in version control. After deployment, verify its status and compilation errors:
SELECT trigger_name, status
FROM user_triggers
WHERE table_name = 'EMPLOYEES';
SELECT name, type, line, position, text
FROM user_errors
WHERE type = 'TRIGGER'
ORDER BY name, sequence;| Risk | Safer practice |
|---|---|
| Hidden business logic | Keep the trigger small and documented |
| Mutating table error | Use a compound trigger |
| Unexpected rollback behavior | Never commit in a normal trigger |
| Disabled or invalid trigger | Check `USER_TRIGGERS` and `USER_ERRORS` |
Exercise
An audit trigger commits its audit insert so that the record survives a rollback of the employee update. What is the main risk?
Show answer
The audit table can claim that a business change occurred even though the change rolled back. Use an autonomous transaction only when this independent behavior is intentional and documented.