SQL Trigger

An SQL trigger is a database object that automatically executes a set of actions or statements in response to a specific event or condition. Triggers are associated with database tables and are triggered by events such as inserts, updates, or deletes on the table.

Here’s an example of creating an SQL trigger:

CREATE TRIGGER trig_name
AFTER INSERT ON table_name
FOR EACH ROW
BEGIN
    -- Trigger actions/statements here
    -- This example simply displays a message
    -- You can perform various operations within the trigger
    SELECT 'Trigger executed' AS message;
END;

In this example, we create a trigger named trig_name that will execute after an insert operation is performed on the table_name table. The FOR EACH ROW clause indicates that the trigger should be executed for each row affected by the insert operation.

Within the BEGIN and END block, you can define the actions or statements that should be executed when the trigger is fired. In this case, the trigger simply performs a SELECT statement to display a message (‘Trigger executed’).

Triggers can be used to enforce data integrity, implement business rules, audit changes, or perform complex calculations. They are a powerful feature of SQL databases that allow you to automate tasks and maintain data consistency.