MySQL triggers offer a powerful mechanism for enforcing data integrity by automatically executing code before or after database operations. This example demonstrates how a BEFORE INSERT
trigger can prevent insertions of rows with future birthdates.
Here's a trigger that blocks INSERTs if the birthdate
is in the future:
<code class="language-sql">CREATE TRIGGER prevent_future_birthdate BEFORE INSERT ON your_table FOR EACH ROW BEGIN IF NEW.birthdate > CURDATE() THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Birthdate cannot be in the future'; END IF; END;</code>
This trigger signals a custom SQLSTATE error, providing a clear message explaining why the insertion failed.
A different approach involves modifying the data within the trigger to violate a NOT NULL
constraint:
<code class="language-sql">CREATE TRIGGER set_birthdate_null BEFORE INSERT ON your_table FOR EACH ROW BEGIN IF NEW.birthdate > CURDATE() THEN SET NEW.birthdate = NULL; END IF; END;</code>
If a NOT NULL
constraint is defined on the birthdate
column, setting it to NULL
will cause the INSERT to fail. This method is less explicit about the reason for failure, however. Remember to replace your_table
with the actual name of your table.
The above is the detailed content of How Can MySQL Triggers Prevent INSERTs Based on Future Birthdates?. For more information, please follow other related articles on the PHP Chinese website!