How BEFORE UPDATE triggers can be used to emulate CHECK CONSTRAINT
for updating values in the table?


As we know that MySQL supports foreign key for referential integrity but it does not support CHECK constraint. But we can emulate them by using triggers. It can be illustrated with the help of an example given below −

Example

Suppose we have a table named ‘car’ which can have the fix syntax registration number like two letters, a dash, three digits, a dash, two letters as follows −

mysql> Create table car (number char(9));
Query OK, 0 rows affected (0.32 sec)

Creating BEFORE UPDATE trigger to emulate CHECK CONSTRAINT for updating the values −

Now, suppose if we will try to update the table with an incorrect value then MySQL is not going to stop us to do so as follows −

mysql> update car set number='AB-2X5-YZ';
Query OK, 1 row affected (0.04 sec)
Rows matched: 1 Changed: 1 Warnings: 0

The above query has updated the incorrect value in the table ‘car’. In the following query we are going to create a BEFORE UPDATE trigger which will prevent us to update incorrect data in the table −

mysql> delimiter //
mysql> create trigger car_update_value before update on car
-> for each row
-> begin
-> if new.number not rlike '^[[:alpha:]]{2}-[[:digit:]]{3}-[[:alpha:]]{2}$'
-> then
->  signal sqlstate '45000' set message_text = 'Not a valid number';
-> end if;
-> end //
Query OK, 0 rows affected (0.11 sec)

mysql> Delimiter ;

mysql> update car set number='AB-2X5-YZ';
ERROR 1644 (45000): Not a valid number

Sai Subramanyam
Sai Subramanyam

Passionate, Curious and Enthusiastic.

Updated on: 22-Jun-2020

50 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements