{"id":30069,"date":"2021-01-18T03:07:47","date_gmt":"2021-01-17T19:07:47","guid":{"rendered":"https:\/\/web.mwwsb.com.my\/pjci\/?post_type=kb&p=30069"},"modified":"2022-09-08T21:33:56","modified_gmt":"2022-09-08T13:33:56","slug":"what-are-mysql-triggers-and-how-to-use-them","status":"publish","type":"kb","link":"https:\/\/www.casbay.com\/guide\/kb\/what-are-mysql-triggers-and-how-to-use-them","title":{"rendered":"What are MySQL triggers and how to use them?"},"content":{"rendered":"\t\t
The MySQL trigger is a database object that is associated with a table. It will be activated when a defined action is executed for the table. Then, the trigger can be executed when you run one of the following MySQL statements on the table:\u00a0INSERT<\/strong>,\u00a0UPDATE<\/strong><\/em>\u00a0and\u00a0DELETE<\/strong><\/em> and it can be invoked before or after the event.\u00a0<\/p> In addition, you can find detailed explanation of the trigger functionality and syntax\u00a0in this article<\/a>.<\/p> In fact, the main requirement for running such MySQL Triggers is having MySQL\u00a0SUPERUSER<\/strong>\u00a0privileges.<\/p> Such privileges can be granted on the\u00a0VPS\u00a0<\/a>and Dedicated Servers<\/a>. Granting\u00a0SUPERUSER<\/strong>\u00a0MySQL privileges to a user hosted on a Shared Server is not possible due to our server setup.<\/p> Here is an example of a MySQL trigger:<\/p> 1. Firstly, we will create the table for which the trigger will be set via SSH.<\/strong><\/p> 2. Next we will define the trigger. It will be executed before every INSERT statement for the people table.<\/p> 3. Then, we will insert two records to check the trigger functionality.<\/p> 4. Lastly, we will check the result.<\/p>mysql>\u00a0CREATE\u00a0TABLE\u00a0people\u00a0(age\u00a0INT,\u00a0name\u00a0varchar(150));<\/pre>
mysql> delimiter \/\/mysql> CREATE TRIGGER agecheck BEFORE INSERT ON people FOR\u00a0EACH<\/strong>\u00a0ROW\u00a0IF\u00a0NEW<\/strong>.age\u00a0<\u00a00\u00a0THEN<\/strong>\u00a0SET\u00a0NEW<\/strong>.age\u00a0=\u00a00;\u00a0END\u00a0IF<\/strong>;\/\/\u00a0Query\u00a0OK,\u00a00\u00a0rows\u00a0affected\u00a0(0.00\u00a0sec)mysql>\u00a0delimiter\u00a0;<\/pre>
mysql>\u00a0INSERT\u00a0INTO\u00a0people\u00a0VALUES\u00a0(-20,\u00a0\u2018Adam\u2019),\u00a0(30,\u00a0\u2018Mark\u2019);Query\u00a0OK,\u00a02\u00a0rows\u00a0affected\u00a0(0.00\u00a0sec)Records:\u00a02\u00a0Duplicates:\u00a00\u00a0Warnings:\u00a00<\/pre>
mysql>\u00a0SELECT *\u00a0FROM\u00a0people;+\u2014\u2014-+\u2014\u2014-+|\u00a0age\u00a0|\u00a0name\u00a0|+\u2014\u2014-+\u2014\u2014-+|\u00a00\u00a0|\u00a0Adam\u00a0||\u00a030\u00a0|\u00a0Mark\u00a0|+\u2014\u2014-+\u2014\u2014-+2\u00a0rows\u00a0in\u00a0set\u00a0(0.00\u00a0sec)<\/pre>\t\t\t\t\t\t<\/div>\n\t\t\t\t<\/div>\n\t\t\t\t