Triggers
Triggers
Trigger is a statement that a system executes automatically when there is any modification to
the database. In a trigger, we first specify when the trigger is to be executed and then the
action to be performed when the trigger executes. Triggers are used to specify certain
integrity constraints and referential constraints that cannot be specified using the constraint
mechanism of SQL.
The trigger is always executed with the specific table in the database. If we remove the table,
all the triggers associated with that table are also deleted automatically.
In Structured Query Language, triggers are called only either before or after the below
events:
1. INSERT Event: This event is called when the new row is entered in the table.
2. UPDATE Event: This event is called when the existing record is changed or modified in
the table.
3. DELETE Event: This event is called when the existing record is removed from the table.
Example:
After the table name, we have to define the row-level or statement-level trigger.
And, at last, we have to write the SQL statements which perform actions on the occurring of
event.
The following query creates the Student_Trigger table in the SQL database:
The following query fires a trigger before the insertion of the student record in the table:
CREATE TRIGGER Student_Table_Marks
BEFORE INSERT
ON
Student_Trigger
FOR EACH ROW
SET new.Student_TotalMarks = new.Student_EnglishMarks + new.Student_PhysicsMarks
+ new.Student_ChemistryMarks + new.Student_MathsMarks,
new.Student_Percentage = ( new.Student_TotalMarks / 400) * 100;
Above SQL statement will create a trigger in the Student_Trigger in which whenever
subjects marks are entered, before inserting this data into the database, the trigger will
compute those two values and insert them with the entered values.
To check the output of the above INSERT statement, you have to type the following SELECT
statement:
Output:
1. SQL provides an alternate way for maintaining the data in the tables.
2. They allow the database users to validate values before inserting and updating.
Also used for protecting the data that was stored in the
database;
DDL Triggers
Output:
DML Triggers