Sub topic 1
What Is a Database Trigger?
Prerequisites
This chapter assumes you can already do the following:
- Write basic SQL:
SELECT,INSERT,UPDATE, andDELETE. - Read and write simple PL/SQL: anonymous blocks, variables,
IFstatements, and exception handling. - Work with tables, views, and sequences.
- Explain what
COMMITandROLLBACKdo in a transaction.
You do not need to have written a trigger before. This chapter builds the working model. Later chapters cover syntax and each kind of trigger in detail.
The Working Model
A database trigger is a named PL/SQL block stored in the database. Oracle runs it automatically when a specified event happens. You never call a trigger yourself. There is no EXEC my_trigger. The event is the call.
Every trigger has three parts:
- Event. The thing that causes it to fire. Most often this is an
INSERT,UPDATE, orDELETEon a table or view. It can also be a DDL statement such asDROP, or a database event such as a user logon. - Timing and level. When the trigger runs relative to the event (
BEFORE,AFTER, orINSTEAD OF), and how often (once per statement, or once per affected row). - Body. The PL/SQL code that runs.
Because a trigger lives in the database, it runs for every session and every tool that causes the event. A web application, a SQL*Plus script, a data loader, and a developer typing in a SQL client all fire the same trigger.
The sketch below shows the simplest possible trigger. It only illustrates the shape. Chapter 3 covers the syntax.
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;
/After this exists, a statement like the following needs no employee_id and no created_at. The trigger fills both in before the row is stored.
INSERT INTO employees (last_name, department_id)
VALUES ('Okafor', 10);How a Trigger Fits into a Statement
A trigger does not run beside your statement. It runs inside it. The trigger executes in the same session and the same transaction as the statement that fired it. That has three consequences:
- If the trigger raises an unhandled exception, Oracle rolls back the whole triggering statement. The row you tried to insert is not stored.
- Changes the trigger makes, such as an insert into an audit table, are part of your transaction. They commit when you commit and disappear when you roll back.
- The statement waits for the trigger. A slow trigger makes every affected statement slow.
The diagram shows the order of events for a BEFORE row trigger on an INSERT.
What Triggers Are Used For
Triggers fit best when a rule must hold no matter which application touches the data. Typical uses:
| Use | Example |
|---|---|
| Derived values | Set a surrogate key from a sequence, or stamp `created_at` and `updated_by`. |
| Complex validation | Reject a salary decrease, which a `CHECK` constraint cannot do because it cannot see the old value. |
| Auditing | Record who changed which row, with old and new values, in a separate table. |
| Making views modifiable | Redirect an `INSERT` on a join view to the base tables (`INSTEAD OF` trigger). |
| Schema protection | Block `DROP TABLE` in a production schema. |
| Event logging | Record logons or server errors. |
Trigger, Constraint, or Application Code?
A trigger is rarely the first tool to reach for. Compare the alternatives.
| Need | Best choice | Why |
|---|---|---|
| A column must not be null, must be unique, or must reference another table | Constraint (`NOT NULL`, `UNIQUE`, `FOREIGN KEY`) | Declarative, optimized by Oracle, and visible in the data dictionary. |
| A value must fall in a range or match a simple expression on the same row | `CHECK` constraint | Simpler and cheaper than a trigger. |
| A default value for a column | `DEFAULT` clause, or an identity column | No code to maintain. |
| A rule that needs the old value, other tables, or procedural logic, and must apply to all clients | Trigger | Enforced for every session. |
| Business logic that is a multi-step process | Stored procedure or application code | Visible, testable, and called explicitly. |
The rule of thumb: use a declarative feature when one exists, and use a trigger when the rule needs procedural logic that must not be bypassed.
Costs and Risks
Triggers are powerful because they are invisible to the caller. That is also their main cost.
- Hidden behavior. A developer reading an
UPDATEstatement cannot see that a trigger also writes to three other tables. Debugging "why did this value change?" often ends in the trigger list. - Performance. A row-level trigger runs once per row. A bulk statement that touches 500,000 rows runs the trigger body 500,000 times, and each run may include SQL. This adds context switching between the SQL and PL/SQL engines.
- Cascading effects. A trigger can run DML that fires other triggers. Chains become hard to predict.
- Restrictions. A row trigger generally cannot query or change the table that is being modified by the statement. Oracle raises
ORA-04091, the mutating table error. A trigger body also cannot issueCOMMITorROLLBACKby default, because it is part of the caller's transaction. Both topics get their own chapters. - Bypass risks and surprises. Some bulk tools, such as direct-path loads, may skip triggers or require them to be disabled. An administrator can disable triggers with
ALTER TABLE ... DISABLE ALL TRIGGERS. A rule that relies only on a trigger can silently stop being enforced.
A Look at the Trigger Families
Oracle groups triggers by what fires them. The next chapter treats these in depth.
| Family | Fires on | Example |
|---|---|---|
| DML trigger | `INSERT`, `UPDATE`, `DELETE` on a table | Audit trail on `employees` |
| INSTEAD OF trigger | DML on a view | Insert through a join view |
| Compound trigger | DML, with several timing points in one unit | Avoiding `ORA-04091` |
| System trigger | DDL or database events | `BEFORE DROP ON SCHEMA`, logon triggers |
Seeing That a Trigger Exists
You can confirm what triggers are attached to a table by querying the data dictionary:
SELECT trigger_name, trigger_type, triggering_event, status
FROM user_triggers
WHERE table_name = 'EMPLOYEES';The STATUS column shows ENABLED or DISABLED. Make this query a habit whenever a table behaves in a way the visible SQL does not explain.
Common Misunderstandings
- "A trigger is like a procedure I can call." It is not callable. Only its event runs it.
- "The trigger runs after my transaction commits." It runs during the statement, before the commit. Rolling back undoes its work too.
- "A trigger runs once per statement." That depends on the level. A
FOR EACH ROWtrigger runs once per row. A statement-level trigger runs once per statement, even if zero rows match. - "Triggers are free validation." Each one adds cost and hidden coupling. Prefer constraints where they can express the rule.
Exercise
A table has a rule: a new order's total must be greater than zero. Another rule says an order's status may never move from SHIPPED back to NEW. Which rule is a natural fit for a CHECK constraint, which one needs a trigger, and why?
Show answer
The "total must be greater than zero" rule fits a CHECK constraint (CHECK (total > 0)) because it depends only on the values in the same row. The status rule needs a trigger, because it must compare the old value (SHIPPED) with the new value (NEW) during an UPDATE. A CHECK constraint can only see the new row, not the old one.
Exercise
A BEFORE INSERT row trigger on orders raises an unhandled exception for one row while a single INSERT ... SELECT is loading 1,000 rows. What happens to the other 999 rows, and to anything the trigger already wrote to an audit table for earlier rows in that statement?
Show answer
Oracle rolls back the entire triggering statement, so none of the 1,000 rows are stored. Audit rows written by the trigger in the same statement are rolled back too, because the trigger runs in the same transaction as the statement. Work done earlier in the transaction by other statements is not undone unless the session rolls back.
Exercise
Name two reasons a rule enforced only by a trigger may stop being enforced, and one design habit that reduces the risk of hidden behavior.
Show answer
The trigger can be disabled (ALTER TRIGGER ... DISABLE or ALTER TABLE ... DISABLE ALL TRIGGERS), and some bulk-loading paths such as direct-path loads can skip or require disabling triggers. To reduce hidden behavior, keep trigger bodies short, move the real logic into a packaged procedure, and document which triggers exist on each table (for example, by checking USER_TRIGGERS).