Hi. Today, let us have a look at an interesting topic in MySQL, Triggers.
For those who don’t know SQL, Structured Query Language (SQL) is a standard computer language for relational database management and data manipulation. MySQL is an example of a Database Management System. Pssst… It is pretty famous.
Photo by Caspar Camille Rubin on Unsplash
Triggers help us instantiate an action when a specific cause is detected. In simple words, perform a specific, pre-defined action when a particular change is caused to the table.
Let us look at an example of what a trigger command in MySQL looks like and later we can discuss its functioning.
DELIMITER $$
CREATE
TRIGGER my_trigger BEFORE INSERT
ON EMPLOYEE
FOR EACH ROW BEGIN
INSERT INTO trigger_test VALUES('add new emp');
END $$
DELIMITER;
The above code creates a trigger which inserts a record with the text ‘add new emp’ in ‘trigger_test’ table of the ‘EMPLOYEE’ database before each record is entered by the user. So, for example, if the user entered 2 records, he/she would see the records in the order:
‘add new emp’, ‘record 1’, ‘add new emp’, ‘record 2’
‘my_trigger’ is the name of the trigger we just created.
You could change the syntax to AFTER INSERT to add the ‘add new emp’ record after each row is added to the table by the user which will look like this:
DELIMITER $$
CREATE
TRIGGER my_trigger AFTER INSERT
ON EMPLOYEE
FOR EACH ROW BEGIN
INSERT INTO trigger_test VALUES('add new emp');
END $$
DELIMITER;
#mysql