Unfortunately MySQL does not support SQL check constraints. You can define them in your DDL query for compatibility reasons but they are just ignored.
There is a simple alternative
You can create BEFORE INSERT
and BEFORE UPDATE
triggers which either cause an error or set the field to its default value when the requirements of the data are not met.
Example for BEFORE INSERT
working after MySQL 5.5
DELIMITER $$
CREATE TRIGGER `test_before_insert` BEFORE INSERT ON `Test`
FOR EACH ROW
BEGIN
IF CHAR_LENGTH( NEW.ID ) < 4 THEN
SIGNAL SQLSTATE '12345'
SET MESSAGE_TEXT := 'check constraint on Test.ID failed';
END IF;
END$$
DELIMITER ;
Prior to MySQL 5.5 you had to cause an error, e.g. call a undefined procedure.
In both cases this causes an implicit transaction rollback.
MySQL does not allow the ROLLBACK statement itself within procedures and triggers.
If you don't want to rollback the transaction ( INSERT / UPDATE should pass even with a failed "check constraint" you can overwrite the value using SET NEW.ID = NULL
which will set the id to the fields default value, doesn't really make sense for an id tho
Edit:
Removed the stray quote.
Concerning the :=
operator:
Unlike =
, the :=
operator is never interpreted as a comparison operator. This means you can use :=
in any valid SQL statement (not just in SET statements) to assign a value to a variable.
https://dev.mysql.com/doc/refman/5.6/en/assignment-operators.html
Concerning backtick identifier quotes:
The identifier quote character is the backtick (“`”)
If the ANSI_QUOTES SQL mode is enabled, it is also permissible to quote identifiers within double quotation marks
http://dev.mysql.com/doc/refman/5.6/en/identifiers.html