0
0
SQLquery~5 mins

Trigger performance considerations in SQL

Choose your learning style9 modes available
Introduction
Triggers automatically run code when data changes. Understanding their performance helps keep your database fast and smooth.
When you want to automatically check or change data after insert, update, or delete.
When you need to keep data consistent without extra manual steps.
When you want to log changes in data for tracking.
When you want to enforce rules that can't be done with simple constraints.
When you want to avoid slowing down your database with heavy trigger code.
Syntax
SQL
CREATE TRIGGER trigger_name
AFTER INSERT ON table_name
FOR EACH ROW
BEGIN
  -- trigger code here
END;
Triggers run automatically after or before data changes.
Keep trigger code simple to avoid slowing down database operations.
Examples
This trigger logs every new employee added.
SQL
CREATE TRIGGER log_insert
AFTER INSERT ON employees
FOR EACH ROW
BEGIN
  INSERT INTO audit_log (action, emp_id) VALUES ('insert', NEW.id);
END;
This trigger updates the timestamp before an order changes.
SQL
CREATE TRIGGER update_timestamp
BEFORE UPDATE ON orders
FOR EACH ROW
BEGIN
  SET NEW.updated_at = CURRENT_TIMESTAMP;
END;
Sample Program
This example creates a trigger that logs inserts into employees. When we add Alice, the audit_log records it.
SQL
CREATE TABLE employees (id INT PRIMARY KEY, name VARCHAR(50));
CREATE TABLE audit_log (action VARCHAR(10), emp_id INT);

CREATE TRIGGER log_insert
AFTER INSERT ON employees
FOR EACH ROW
BEGIN
  INSERT INTO audit_log (action, emp_id) VALUES ('insert', NEW.id);
END;

INSERT INTO employees (id, name) VALUES (1, 'Alice');
SELECT * FROM audit_log;
OutputSuccess
Important Notes
Triggers run inside the same transaction as the data change, so slow triggers slow down inserts/updates/deletes.
Avoid complex queries or loops inside triggers to keep performance good.
Test triggers carefully to prevent unexpected slowdowns or errors.
Summary
Triggers run automatically on data changes to help automate tasks.
Keep trigger code simple and fast to avoid slowing your database.
Use triggers wisely to maintain data integrity and logging.