Junior
What is a trigger?
sobes.tech AI
Answer from AI
A trigger is a special stored procedure in a database that is automatically executed when a specific event occurs.
Events that invoke triggers typically include:
INSERT: adding new rows to a table.UPDATE: modifying existing rows in a table.DELETE: removing rows from a table.
Triggers can be invoked at different times relative to the event:
BEFORE: before the event is executed.AFTER: after the event is executed.INSTEAD OF: instead of executing the event (often used with views).
Examples of trigger usage:
- Maintaining data integrity: Automatic checking or modification of data during insert/update.
- Audit logging: Recording information about data changes in a separate log table.
- Data synchronization: Automatic updating of related tables.
- Executing complex business rules: Initiating additional actions under certain conditions.
Triggers are defined at the table level and can reference old and new values of the row that was changed.
-- Example syntax (SQL)
CREATE TRIGGER audit_log
AFTER INSERT ON users
FOR EACH ROW
BEGIN
INSERT INTO audit (user_id, action, timestamp)
VALUES (NEW.id, 'insert', NOW());
END;
It is important to use triggers with caution, as they can complicate debugging and affect database performance.