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

MySQLMySQLi Database

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)

mysql> Insert into car values('AB-235-YZ');
Query OK, 1 row affected (0.10 sec)

The above value is a valid one but what about the value that we are going to insert in the next query.

mysql> insert into car values('AB-2X5-YZ');
Query OK, 1 row affected (0.04 sec)

The above value is not a valid one because it contains a character between digits which is against the fixed syntax we are using.

Creating BEFORE INSERT trigger to emulate CHECK CONSTRAINT for inserting the values −

Now, we can create a trigger as follows to prevent such kind of insertion −

mysql> delimiter //
mysql> create trigger car_insert_value before insert 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.15 sec)
mysql> Delimiter ;

mysql> Delete from car;
Query OK, 2 rows affected (0.06 sec)

Now, when we will try to insert the incorrect number, the above-created trigger will stop us to do so and will throw an error as follows −

mysql> insert into car values('AB-2X5-YZ');
ERROR 1644 (45000): Not a Valid Number

But, we can insert the valid values as follows −

mysql> insert into car values('AB-235-YZ');
Query OK, 1 row affected (0.04 sec)
raja
Updated on 22-Jun-2020 13:02:44

Advertisements