Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a MySQL trigger simulate a CHECK constraint? [duplicate]

I want to use the CHECK constraint in MySQL, but it is not supported. (Unlike other RDBMS, it will understand but not enforce the CHECKs.)

I have seen some workarounds with triggers. But they tend to set a default value to the field in question instead of returning an error.

Is it possible to construct a trigger that returns an error if a condition is not met?

Ultimately I want a trigger that copies a CHECK constraint.

like image 750
smnsvane Avatar asked Mar 16 '12 09:03

smnsvane


People also ask

How a trigger is different from a check constraint?

BEFORE triggers, unlike check constraints, are not restricted to access other values in the same row of the same table. During a SET INTEGRITY operation on a table after a LOAD operation, triggers (including BEFORE triggers) are not executed. Check constraints, however, are verified.

Why use a trigger over a check constraint?

Check constraints are fired with each row. Triggers can be written so all inserted rows are checked as a single batch and that is often faster. Also, a trigger can be written so it is only fired if some column(s) of interest are set/modified.

Can a trigger include select statement?

The trigger event that initiates the trigger action can be an INSERT, DELETE, UPDATE, or a SELECT statement. The MERGE statement can also be the triggering event for an UPDATE, DELETE, or INSERT trigger.

Are triggers constraints?

A database trigger is not the same as an integrity constraint. A database trigger defined to enforce an integrity rule does not check data already loaded into a table. Therefore, it is recommended that you use a trigger only when the integrity rule cannot be enforced by an integrity constraint.


1 Answers

when you are updating data :

delimiter $$
create trigger chk_stats1 before update on stats 
  for each row 
   begin  
    if  new.month>12 then
        SIGNAL SQLSTATE '45000'   
        SET MESSAGE_TEXT = 'Cannot add or update row: only';
      end if; 
      end; 
      $$

when you are inserting data :

   delimiter $$
    create trigger chk_stats before insert on stats 
      for each row 
       begin  
      if  new.month>12 then
       SIGNAL SQLSTATE '45000'   
       SET MESSAGE_TEXT = 'Cannot add or update row: only';
       end if; 
    end; 
    $$

these trigger will work as check constraint ,work before insert or update and check month, if month >12 gives error .

like image 165
abhishek ringsia Avatar answered Sep 17 '22 15:09

abhishek ringsia