CREATE TRIGGER
Create a trigger that automatically executes one or more SQL statements when a row is inserted into, updated in, or deleted from a table.
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
A BEFORE trigger fires before the triggering statement modifies the row. Use BEFORE triggers to validate or transform data before it is written.
- The
NEW row reference contains the values that are about to be written. For INSERT triggers, NEW is the row being inserted. For UPDATE triggers, NEW contains the updated values.
- The
OLD row 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
An AFTER trigger fires after the triggering statement has modified the row. Use AFTER triggers for logging, auditing, or cascading changes to other tables.
- The
NEW and OLD row references are available with the same semantics as BEFORE triggers.
- The row has already been written when the trigger body executes.
INSTEAD OF Triggers
INSTEAD OF triggers are not yet supported in Turso. CREATE TRIGGER ... INSTEAD OF ... returns an error.
In SQLite, an INSTEAD OF trigger can only be created on a view and fires in place of the triggering INSERT, UPDATE, or DELETE, allowing you to make views writable. Turso parses this syntax but does not yet execute it.
Row References
Inside a trigger body, NEW and OLD are special row references that provide access to column values.
WHEN Clause
The optional WHEN 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 the OF clause, the trigger fires on any UPDATE to the table.
RAISE Function
The RAISE 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