Course
Create Trigger
MySQL Tutorial
This SQL tutorial is structured for beginners to guide them from the foundational concepts to advanced data manipulation and querying techniques in SQL. By the end of this tutorial, you will have developed a robust understanding of SQL, equipping you with the knowledge to efficiently manage and analyze data across various database systems. This guide sets the stage for your growth into a skilled data professional, ready to tackle complex data challenges and contribute to the field of data analysis and database management.
CREATE TRIGGER
Triggers are generally defined as responses to an event. For instance, when we hover a mouse-pointer on a drop-down menu of a website, a various set of options to navigate through this website are then displayed. Here, the hovering of the mouse-pointer is an event while the display of options in the drop-down menu is a result of trigger execution. This concept is also introduced in MySQL.
Triggers in MySQL are stored programs similar to procedures. These can be created on a table, schema, view and database that are associated with an event and whenever an event occurs the respective trigger is invoked.
Triggers are, in fact, written to be executed in response to any of the following events −
- A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)
- A database definition (DDL) statement (CREATE, ALTER, or DROP).
- A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN).
Creating Trigger in MySQL
You can create a trigger using the CREATE TRIGGER Statement.
Syntax
Following is the syntax of the MySQL CREATE TRIGGER Statement.
CREATE TRIGGER trigger_nametrigger_time trigger_eventON table_name FOR EACH ROWBEGIN...END;
Where,
- trigger_name is the name of the trigger you need to create
- trigger_time is the time of trigger activation
- trigger_event can be INSERT, UPDATE, or DELETE. This event causes the trigger to be invoked.
- table_name is the name of the table to which the trigger is associated with.
Example
Assume we have created a table with name student as shown below −
CREATE TABLE STUDENT( Name varchar(35), Age INT, Score INT);
Following query creates a trigger, this will set the score value 0 if you enter a value that is less than 0 as score.
DELIMITER //CREATE TRIGGER sample_trigger BEFORE INSERT ON STUDENT FOR EACH ROWBEGINIF NEW.Score < 0 THEN SET NEW.Score = 0;END IF;END //DELIMITER ;
Verification
If you try to insert records in the student table and if you use a value that is less than 0 as age it will be automatically set to 0.
INSERT INTO STUDENT VALUES('Jeevan', 22, 8),('Raghav', 26, -3),('Pooja', 21, -9),('Devi', 30, 9);
The STUDENT table created will have the following records −
As we can see, there are no negative values inserted in the table as they are all replaced with zeroes.
Creating Trigger Using a Client Program
We can also Create a trigger using a client program.
Syntax
PHPNodeJSJavaPython
To Create a Trigger through a PHP program, we need to execute the CREATE statement using the mysqli function named query() as follows −
$sql = "CREATE TRIGGER testTrigger AFTER UPDATE ON Student FOR EACH ROW INSERT INTO Student SET action = 'update', Name = OLD.Name, age = OLD.age, score = OLD.score";$mysqli->query($sql);
Example
Following are the programs −
PHPNodeJSJavaPython
$dbhost = 'localhost';$dbuser = 'root';$dbpass = 'password';$db = 'TUTORIALS';$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $db);if($mysqli->connect_errno ) { printf("Connect failed: %s", $mysqli->connect_error); exit();}//printf('Connected successfully.');$sql = "CREATE TRIGGER testTrigger AFTER UPDATE ON Student FOR EACH ROW INSERT INTO Student SET action = 'update', Name = OLD.Name, age = OLD.age, score = OLD.score";if($mysqli->query($sql)){ printf("Trigger created successfully...!");}if($mysqli->error){ printf("Failed..!" , $mysqli->error);}$mysqli->close();
Output
The output obtained is as follows −
Trigger created successfully...!