Database Triggers: Principles, Types, and a Practical Guide
This article explains how database triggers work, breaks down their core components, timing options, and granularity, and walks through common trigger types and use cases. It also covers key pitfalls and engineering best practices for using triggers safely and effectively.
1. What Is a Trigger: An Event-Driven Special Program Block
A trigger is a special kind of stored procedure bound to a table, view, or schema. It is never called explicitly and takes no parameters. Instead, it is invoked implicitly when a specific event occurs. The event can be a data manipulation statement (INSERT, UPDATE, DELETE), a schema-level structural change, or a system-level event such as a database startup or shutdown.
The key to understanding triggers is their passive nature. A regular stored procedure is initiated by the application, and the timing of the call is fully controllable. A trigger, by contrast, hands execution control to the database itself: as soon as the target event occurs, the trigger body runs. This makes triggers a natural fit for logic that must happen together with a data change, such as fallback integrity checks, change tracking, and derived-column maintenance. It also means that poorly designed triggers can scatter logic inside the data structures, making troubleshooting harder.
2. Basic Syntax and Four Core Components
A trigger typically consists of four parts: a name, a triggering event, a timing, and a body. Trigger restrictions and execution granularity can be added when needed.
CREATE [OR REPLACE] TRIGGER trigger_name{ BEFORE | AFTER | INSTEAD OF } triggering_event[ WHEN trigger_condition ][ FOR EACH ROW ]trigger_body;
- Trigger name: unique within its schema.
OR REPLACEmakes iterative rebuilding easier. - Triggering event:
triggering_eventspecifies what fires the trigger, typically a data manipulation event on a table or view. - Trigger restriction: the condition in the
WHENclause is evaluated first, and the body runs only if the result is true. This acts as a cheap filter that avoids entering the body logic unnecessarily. - Body:
trigger_bodyis the statement block that actually executes, usually a logic unit written in a procedural language.
3. Three Timing Options
BEFORE runs before the data is written. It is suitable for modifying values about to be stored, filling in default information, or blocking invalid data. AFTER runs after the write completes. It is suitable for logging, maintaining summary tables, and propagating changes to related structures. INSTEAD OF applies only to views. It rewrites update operations against a view into real operations on the underlying tables, making complex views updatable.
A practical rule for choosing: put logic that affects “what ultimately gets written” in BEFORE, put logic that performs follow-up actions based on “what has already been written” in AFTER, and use INSTEAD OF for rewriting view updates.
4. Statement-Level vs. Row-Level: Granularity Determines Semantics
A statement-level trigger runs only once during the execution of a data modification statement, regardless of whether the statement affects zero rows, one row, or tens of thousands of rows. It suits summary actions unrelated to row counts, such as recording “who deleted data and when.”
CREATE TABLE orderdetails_tablelog (who VARCHAR2(40),oper_date DATE);CREATE OR REPLACE TRIGGER dele_orderdetailsAFTER DELETE ON orderdetailsBEGININSERT INTO orderdetails_tablelog (who, oper_date)VALUES (USER, SYSDATE);END;
A row-level trigger is declared with FOR EACH ROW and executes once per affected row. It can access the before and after values through pseudo-records: :OLD refers to the old value and :NEW to the new value. On insert, usually only :NEW is available; on delete, usually only :OLD; on update, both exist. To limit columns, you can write UPDATE OF column_list, which fires only when the specified columns are updated.
Note in particular that row-level triggers are invoked repeatedly during bulk data operations. Patterns that write logs row by row or query tables row by row can easily become performance bottlenecks, and should preferably be rewritten as statement-level or set-based processing.
5. Three Common Forms by Event Category
- Data manipulation triggers: target INSERT, UPDATE, and DELETE on tables or views. They are the most common type, used for validation, change tracking, derived-column generation, and cross-table synchronization.
- Instead-of triggers: bound to views, they turn views that cannot be updated directly into operable objects, often used to hide the complexity of multi-table joins.
- System triggers: respond to events such as logins and logouts, instance startup and shutdown, and schema changes. They are mostly used for environment auditing and security monitoring.
6. Typical Use Cases
Fallback data integrity: when constraints are limited in expressiveness, use BEFORE triggers to enforce cross-field and cross-table business rules, rejecting invalid data before it is written.
Audit trails: use AFTER triggers to write the operator, timestamp, and before/after snapshots into a log table, forming a traceable chain. The log table should be append-only, not modified.
Derived columns and sequence values: fetch a number from a sequence before insert and assign it to the primary key or a business number, avoiding inconsistent rules implemented separately in the application layer.
Multi-table synchronization: after a change to the main table, keep detail or summary data in sync to ensure data consistency across read and write paths.
It is worth emphasizing that if the business already has mature field defaults, virtual columns, or constraint mechanisms, declarative capabilities should be preferred, and triggers should handle only what declarative means cannot cover.
7. Common Pitfalls and Engineering Recommendations
- Observability gap from implicit execution: always add necessary logging and exception handling in the body to avoid silent failures.
- Cascading triggers: a write from one trigger may fire another, forming a chain of calls that is hard to trace. Keep the chain shallow and clear.
- Set-based thinking: rewrite row-level logic as set operations wherever possible to reduce context-switching overhead.
- Alignment with transaction boundaries: a trigger runs within the transaction of the triggering statement, and an exception in the body affects the result of the entire statement, so it must align with business expectations.
- Maintainability: name triggers to reflect “table + timing + action,” manage them with versioned scripts, and avoid logic black boxes.
In cloud environments, this kind of logic is typically used together with common capabilities such as log services, monitoring and alerting, and object storage, sending the audit data produced by triggers for archival and alerting to form a complete governance loop. The relevant general product categories of Baidu AI Cloud can also serve as a reference direction for hosting such data pipelines.
