Course
Before Update 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.
Before Update Trigger
Triggers in MySQL are of two types: Before Triggers and After Triggers for various SQL operations like insertion, deletion and update. As we have already learned in previous chapters, the After Update Trigger is executed immediately after a value is updated in a row of a database table. Here, let us learn more about BEFORE UPDATE trigger.
MySQL Before Update Trigger
The Before Update Trigger is a row-level trigger supported by the MySQL database. It is type of special stored procedure which is executed automatically before a value is updated in a row of a database table.
A row-level trigger is a type of trigger that goes off every time a row is modified. Simply, for every single transaction made in a table (like insertion, deletion, update), one trigger acts automatically.
Whenever an UPDATE statement is executed in the database, the trigger is set to go off first followed by the updated value.
Syntax
Following is the syntax to create the BEFORE UPDATE trigger in MySQL −
CREATE TRIGGER trigger_nameBEFORE UPDATE ON table_name FOR EACH ROWBEGIN -- trigger bodyEND;
Example
Let us first create a table named USERS containing the details of users of an application. Use the following CREATE TABLE query to do so −
CREATE TABLE USERS( ID INT AUTO_INCREMENT, NAME VARCHAR(100) NOT NULL, AGE INT NOT NULL, birthDATE VARCHAR(100), PRIMARY KEY(ID));
Insert values into the USERS table using the regular INSERT statement as shown below −
INSERT INTO USERS (Name, Age, birthDATE) VALUES ('Sasha', 23, '24/06/1999');('Alex', 21, '12/01/2001');
The USERS table is created as follows −
Creating the trigger:
Using the following CREATE TRIGGER statement, create a new trigger 'before_update_trigger' on the USERS table to display a customized error using SQLSTATE as follows −
DELIMITER //CREATE TRIGGER before_update_trigger BEFORE UPDATE ON USERS FOR EACH ROWBEGIN IF NEW.AGE < 0 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Age Cannot be Negative';END IF;END //DELIMITER ;
Update values of the USERS table using the regular UPDATE statement −
UPDATE USERS SET AGE = -1 WHERE NAME = 'Sasha';
Output
An error is displayed as the output for this query −
ERROR 1644 (45000): Age Cannot be Negative
Before Update Trigger Using a Client Program
We can also execute the Before Update Trigger using a client program instead of SQL queries directly.
Syntax
PHPNodeJSJavaPython
To execute the Before Update Trigger through a PHP program, we need to execute the CREATE TRIGGER statement using the mysqli function query() as follows −
$sql = "CREATE TRIGGER before_update_trigger BEFORE UPDATE ON SAMPLE FOR EACH ROWBEGINIF NEW.AGE < 0 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Age Cannot be Negative';END IF;END";$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 before_update_trigger BEFORE UPDATE ON SAMPLE FOR EACH ROWBEGINIF NEW.AGE < 0 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Age Cannot be Negative';END IF;END";if($mysqli->query($sql)){ printf("Trigger created successfully...!\n");}$q = "UPDATE SAMPLE SET AGE = -1 WHERE NAME = 'Sasha'";$result = $mysqli->query($q);if ($result == true) { printf("Record updated successfully...!\n");}if($mysqli->error){ printf("Error message: " , $mysqli->error);}$mysqli->close();
Output
The output obtained is as follows −
Trigger created successfully...!PHP Fatal error: Uncaught mysqli_sql_exception: Age Cannot be Negative