Create and Delete a Trigger
This lesson shows how a trigger is created and demonstrates how it automatically updates an event log. We also show how to drop a trigger in this lesson.
We'll cover the following
Creating a Trigger
A trigger is associated with an event and runs automatically when the event occurs. Triggers can be associated with 6 types of events in MySQL which are; before data is inserted into the table, after data is inserted into the table, before data is updated, after data is updated, before data is deleted, and after data is deleted.
A trigger must be associated with a table. Triggers without a table cannot exist in MySQL. Every trigger associated with a table must have a unique name but the same trigger name can be used with different tables. The CREATE TRIGGER statement is used to create a new trigger. A trigger can be defined before or after an event and the time should be defined using keywords BEFORE or AFTER. The events that cause the trigger to execute are specified as INSERT, UPDATE, or DELETE.
To delete a trigger, the DROP TRIGGER statement is used. Since triggers are associated with tables, when tables are dropped the associated triggers automatically get dropped. In case we want to delete a trigger that belongs to another database, the name of the database is specified before the trigger name.
Syntax
CREATE TRIGGER trigger_name trigger_time trigger_event
ON table_name
FOR EACH ROW
trigger_body
DROP TRIGGER [IF EXISTS] [database_name.]trigger_name;
Connect to the terminal below by clicking in the widget. Once connected, the command line prompt will show up. Enter or copy-paste the command ./DataJek/Lessons/46lesson.sh and wait for the mysql prompt to start-up.
Get hands-on with 1400+ tech skills courses.