CREATE TRIGGER
This feature is experimental and must be enabled before use.
Syntax
Description
A trigger defines a set of SQL statements that run automatically when a specified data modification event occurs on a table or view. Triggers execute within the same transaction as the statement that fired them — if the transaction is rolled back, the trigger’s effects are also rolled back.Parameters
Trigger Timing
BEFORE Triggers
ABEFORE trigger fires before the triggering statement modifies the row. Use BEFORE triggers to validate or transform data before it is written.
- The
NEWrow reference contains the values that are about to be written. For INSERT triggers,NEWis the row being inserted. For UPDATE triggers,NEWcontains the updated values. - The
OLDrow reference is available in UPDATE and DELETE triggers and contains the current values before modification. - If a BEFORE trigger raises an error, the triggering operation is aborted for that row.
AFTER Triggers
AnAFTER trigger fires after the triggering statement has modified the row. Use AFTER triggers for logging, auditing, or cascading changes to other tables.
- The
NEWandOLDrow references are available with the same semantics as BEFORE triggers. - The row has already been written when the trigger body executes.
INSTEAD OF Triggers
AnINSTEAD OF trigger can only be created on a view. It fires in place of the triggering INSERT, UPDATE, or DELETE, allowing you to make views writable.
- The actual INSERT, UPDATE, or DELETE on the view does not execute. The trigger body is responsible for performing the desired changes on the underlying tables.
Row References
Inside a trigger body,NEW and OLD are special row references that provide access to column values.
WHEN Clause
The optionalWHEN clause filters which rows cause the trigger body to execute. The expression can reference NEW and OLD columns.
UPDATE OF Columns
For UPDATE triggers, you can restrict the trigger to fire only when specific columns are modified. Without theOF clause, the trigger fires on any UPDATE to the table.
RAISE Function
TheRAISE function is used inside trigger bodies (and other contexts) to interrupt execution and signal an error. It takes one of four forms:
Multiple Statements
A trigger body can contain multiple SQL statements separated by semicolons. The statements execute in order within the same transaction.Examples
Audit Logging Trigger
Track all changes to a table with an audit log.Validation Trigger
Enforce business rules before data is written.Cascading Update Trigger
Propagate changes to related tables.See Also
- DROP TRIGGER for removing triggers
- CREATE VIEW for views that can use INSTEAD OF triggers
- INSERT, UPDATE, DELETE for the statements that fire triggers