Trigger In Sql in SQL
A Trigger in SQL is a special kind of stored procedure that automatically executes (or fires) when certain events occur on a table or view. Triggers are mainly used for enforcing business rules, auditing, or maintaining data integrity.
? Key Features of Triggers
Automatic execution: Runs in response to specific data modification events (
INSERT,UPDATE, orDELETE).Associated with tables or views.
Can execute before or after the event.
Can access the old and new data values involved in the operation.
Helps implement complex validations and audit trails without manual intervention.
Types of Triggers
| Trigger Type | When It Fires | Purpose |
|---|---|---|
| BEFORE Trigger | Before the data modification event | Validate or modify data before change |
| AFTER Trigger | After the data modification event | Audit, logging, or cascading changes |
| INSTEAD OF Trigger | Instead of the operation (mainly on views) | Customize behavior on views |
Basic Syntax (Example: SQL Server)
CREATE TRIGGER trigger_nameON table_nameAFTER INSERT, UPDATE, DELETEASBEGIN -- Trigger logic hereEND;Example: Audit Insertions
CREATE TRIGGER trg_AuditInsertON EmployeesAFTER INSERTASBEGIN INSERT INTO AuditLog (EmployeeID, Action, ActionDate) SELECT EmployeeID, 'INSERT', GETDATE() FROM inserted;END;insertedis a special table holding newly inserted rows.
Notes
Triggers can affect performance if complex or poorly designed.
Use carefully to avoid recursion or unintended side effects.
Syntax and capabilities vary across database systems (e.g., MySQL, Oracle, SQL Server, PostgreSQL).
If you want, I can provide a trigger example for your specific database or use case!