Suppose I have an attribute called phone number and I would like to enforce certain validity on the entries to this field. Can I use regular expression for this purpose, since Regular Expression is very flexible at defining constraints.
Yes, you can. MySQL supports regex (http://dev.mysql.com/doc/refman/5.6/en/regexp.html) and for data validation you should use a trigger since MySQL doesn't support CHECK constraint (you can always move to PostgreSQL as an alternative:). NB! Be aware that even though MySQL does have CHECK constraint construct, unfortunately MySQL (so far 5.6) does not validate data against check constraints. According to http://dev.mysql.com/doc/refman/5.6/en/create-table.html: "The CHECK clause is parsed but ignored by all storage engines."
You can add a check constraint for a column phone:
CREATE TABLE data (
phone varchar(100)
);
DELIMITER $$
CREATE TRIGGER trig_phone_check BEFORE INSERT ON data
FOR EACH ROW
BEGIN
IF (NEW.phone REGEXP '^(\\+?[0-9]{1,4}-)?[0-9]{3,10}$' ) = 0 THEN
SIGNAL SQLSTATE '12345'
SET MESSAGE_TEXT = 'Wroooong!!!';
END IF;
END$$
DELIMITER ;
INSERT INTO data VALUES ('+64-221221442'); -- should be OK
INSERT INTO data VALUES ('+64-22122 WRONG 1442'); -- will fail with the error: #1644 - Wroooong!!!
However you should not rely merely on MySQL (data layer in your case) for data validation. The data should be validated on all levels of your app.
MySQL 8.0.16 (2019-04-25) and MariaDB 10.2.1 (2016-04-18) now not only parse CHECK constraint but also enforces it.
MySQL: https://dev.mysql.com/doc/refman/8.0/en/create-table-check-constraints.html
MariaDB: https://mariadb.com/kb/en/constraint/
Actually, we can can set regular expression within check constraints in MySQL.
Eg.,:
create table fk
(
empid int not null unique,
age int check(age between 18 and 60),
email varchar(20) default 'N/A',
secondary_email varchar(20) check(secondary_email RLIKE'^[a-zA-Z]#[a-zA-Z0-9]\.[a-z,A-Z]{2,4}'),
deptid int check(deptid in(10,20,30))
)
;
This INSERT query will work:
insert into fk values(1,19,'a#a.com','a#b.com', 30);
This INSERT query will not work:
insert into fk values(2,19,'a#a.com','a#bc.com', 30);
Related
First I created a table like
CREATE TABLE Customer (
SD integer CHECK (SD > 0),
Last_Name varchar (30),
First_Name varchar(30)
);
and then inserted values in that table
INSERT INTO Customer values ('-2','abc','zz');
MySQL doesn't show an error, it accepted the values.
MySQL 8.0.16 is the first version that supports CHECK constraints.
Read https://dev.mysql.com/doc/refman/8.0/en/create-table-check-constraints.html
If you use MySQL 8.0.15 or earlier, the MySQL Reference Manual says:
The CHECK clause is parsed but ignored by all storage engines.
Try a trigger...
mysql> delimiter //
mysql> CREATE TRIGGER trig_sd_check BEFORE INSERT ON Customer
-> FOR EACH ROW
-> BEGIN
-> IF NEW.SD<0 THEN
-> SET NEW.SD=0;
-> END IF;
-> END
-> //
mysql> delimiter ;
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
CHECK constraints are ignored by MySQL as explained in a miniscule comment in the docs: CREATE TABLE
The CHECK clause is parsed but ignored by all storage engines.
The CHECK constraint doesn't seem to be implemented in MySQL.
See this bug report: https://bugs.mysql.com/bug.php?id=3464
As mentioned by joanq MariaDB now seems to support CHECK constraints among other goodies:
"Support for CHECK CONSTRAINT (MDEV-7563)."
https://mariadb.com/kb/en/mariadb/mariadb-1021-release-notes/
Check constraints are supported as of version 8.0.15 (yet to be released)
https://bugs.mysql.com/bug.php?id=3464
[23 Jan 16:24] Paul Dubois
Posted by developer: Fixed in 8.0.15.
Previously, MySQL permitted a limited form of CHECK constraint syntax,
but parsed and ignored it. MySQL now implements the core features of
table and column CHECK constraints, for all storage engines.
Constraints are defined using CREATE TABLE and ALTER TABLE statements.
Update to MySQL 8.0.16 to use checks:
As of MySQL 8.0.16, CREATE TABLE permits the core features of table
and column CHECK constraints, for all storage engines. CREATE TABLE
permits the following CHECK constraint syntax, for both table
constraints and column constraints
MySQL Checks Documentation
try with set sql_mode = 'STRICT_TRANS_TABLES' OR SET sql_mode='STRICT_ALL_TABLES'
First I created a table like
CREATE TABLE Customer (
SD integer CHECK (SD > 0),
Last_Name varchar (30),
First_Name varchar(30)
);
and then inserted values in that table
INSERT INTO Customer values ('-2','abc','zz');
MySQL doesn't show an error, it accepted the values.
MySQL 8.0.16 is the first version that supports CHECK constraints.
Read https://dev.mysql.com/doc/refman/8.0/en/create-table-check-constraints.html
If you use MySQL 8.0.15 or earlier, the MySQL Reference Manual says:
The CHECK clause is parsed but ignored by all storage engines.
Try a trigger...
mysql> delimiter //
mysql> CREATE TRIGGER trig_sd_check BEFORE INSERT ON Customer
-> FOR EACH ROW
-> BEGIN
-> IF NEW.SD<0 THEN
-> SET NEW.SD=0;
-> END IF;
-> END
-> //
mysql> delimiter ;
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
CHECK constraints are ignored by MySQL as explained in a miniscule comment in the docs: CREATE TABLE
The CHECK clause is parsed but ignored by all storage engines.
The CHECK constraint doesn't seem to be implemented in MySQL.
See this bug report: https://bugs.mysql.com/bug.php?id=3464
As mentioned by joanq MariaDB now seems to support CHECK constraints among other goodies:
"Support for CHECK CONSTRAINT (MDEV-7563)."
https://mariadb.com/kb/en/mariadb/mariadb-1021-release-notes/
Check constraints are supported as of version 8.0.15 (yet to be released)
https://bugs.mysql.com/bug.php?id=3464
[23 Jan 16:24] Paul Dubois
Posted by developer: Fixed in 8.0.15.
Previously, MySQL permitted a limited form of CHECK constraint syntax,
but parsed and ignored it. MySQL now implements the core features of
table and column CHECK constraints, for all storage engines.
Constraints are defined using CREATE TABLE and ALTER TABLE statements.
Update to MySQL 8.0.16 to use checks:
As of MySQL 8.0.16, CREATE TABLE permits the core features of table
and column CHECK constraints, for all storage engines. CREATE TABLE
permits the following CHECK constraint syntax, for both table
constraints and column constraints
MySQL Checks Documentation
try with set sql_mode = 'STRICT_TRANS_TABLES' OR SET sql_mode='STRICT_ALL_TABLES'
First I created a table like
CREATE TABLE Customer (
SD integer CHECK (SD > 0),
Last_Name varchar (30),
First_Name varchar(30)
);
and then inserted values in that table
INSERT INTO Customer values ('-2','abc','zz');
MySQL doesn't show an error, it accepted the values.
MySQL 8.0.16 is the first version that supports CHECK constraints.
Read https://dev.mysql.com/doc/refman/8.0/en/create-table-check-constraints.html
If you use MySQL 8.0.15 or earlier, the MySQL Reference Manual says:
The CHECK clause is parsed but ignored by all storage engines.
Try a trigger...
mysql> delimiter //
mysql> CREATE TRIGGER trig_sd_check BEFORE INSERT ON Customer
-> FOR EACH ROW
-> BEGIN
-> IF NEW.SD<0 THEN
-> SET NEW.SD=0;
-> END IF;
-> END
-> //
mysql> delimiter ;
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
CHECK constraints are ignored by MySQL as explained in a miniscule comment in the docs: CREATE TABLE
The CHECK clause is parsed but ignored by all storage engines.
The CHECK constraint doesn't seem to be implemented in MySQL.
See this bug report: https://bugs.mysql.com/bug.php?id=3464
As mentioned by joanq MariaDB now seems to support CHECK constraints among other goodies:
"Support for CHECK CONSTRAINT (MDEV-7563)."
https://mariadb.com/kb/en/mariadb/mariadb-1021-release-notes/
Check constraints are supported as of version 8.0.15 (yet to be released)
https://bugs.mysql.com/bug.php?id=3464
[23 Jan 16:24] Paul Dubois
Posted by developer: Fixed in 8.0.15.
Previously, MySQL permitted a limited form of CHECK constraint syntax,
but parsed and ignored it. MySQL now implements the core features of
table and column CHECK constraints, for all storage engines.
Constraints are defined using CREATE TABLE and ALTER TABLE statements.
Update to MySQL 8.0.16 to use checks:
As of MySQL 8.0.16, CREATE TABLE permits the core features of table
and column CHECK constraints, for all storage engines. CREATE TABLE
permits the following CHECK constraint syntax, for both table
constraints and column constraints
MySQL Checks Documentation
try with set sql_mode = 'STRICT_TRANS_TABLES' OR SET sql_mode='STRICT_ALL_TABLES'
First I created a table like
CREATE TABLE Customer (
SD integer CHECK (SD > 0),
Last_Name varchar (30),
First_Name varchar(30)
);
and then inserted values in that table
INSERT INTO Customer values ('-2','abc','zz');
MySQL doesn't show an error, it accepted the values.
MySQL 8.0.16 is the first version that supports CHECK constraints.
Read https://dev.mysql.com/doc/refman/8.0/en/create-table-check-constraints.html
If you use MySQL 8.0.15 or earlier, the MySQL Reference Manual says:
The CHECK clause is parsed but ignored by all storage engines.
Try a trigger...
mysql> delimiter //
mysql> CREATE TRIGGER trig_sd_check BEFORE INSERT ON Customer
-> FOR EACH ROW
-> BEGIN
-> IF NEW.SD<0 THEN
-> SET NEW.SD=0;
-> END IF;
-> END
-> //
mysql> delimiter ;
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
CHECK constraints are ignored by MySQL as explained in a miniscule comment in the docs: CREATE TABLE
The CHECK clause is parsed but ignored by all storage engines.
The CHECK constraint doesn't seem to be implemented in MySQL.
See this bug report: https://bugs.mysql.com/bug.php?id=3464
As mentioned by joanq MariaDB now seems to support CHECK constraints among other goodies:
"Support for CHECK CONSTRAINT (MDEV-7563)."
https://mariadb.com/kb/en/mariadb/mariadb-1021-release-notes/
Check constraints are supported as of version 8.0.15 (yet to be released)
https://bugs.mysql.com/bug.php?id=3464
[23 Jan 16:24] Paul Dubois
Posted by developer: Fixed in 8.0.15.
Previously, MySQL permitted a limited form of CHECK constraint syntax,
but parsed and ignored it. MySQL now implements the core features of
table and column CHECK constraints, for all storage engines.
Constraints are defined using CREATE TABLE and ALTER TABLE statements.
Update to MySQL 8.0.16 to use checks:
As of MySQL 8.0.16, CREATE TABLE permits the core features of table
and column CHECK constraints, for all storage engines. CREATE TABLE
permits the following CHECK constraint syntax, for both table
constraints and column constraints
MySQL Checks Documentation
try with set sql_mode = 'STRICT_TRANS_TABLES' OR SET sql_mode='STRICT_ALL_TABLES'
Suppose I have an attribute called phone number and I would like to enforce certain validity on the entries to this field. Can I use regular expression for this purpose, since Regular Expression is very flexible at defining constraints.
Yes, you can. MySQL supports regex (http://dev.mysql.com/doc/refman/5.6/en/regexp.html) and for data validation you should use a trigger since MySQL doesn't support CHECK constraint (you can always move to PostgreSQL as an alternative:). NB! Be aware that even though MySQL does have CHECK constraint construct, unfortunately MySQL (so far 5.6) does not validate data against check constraints. According to http://dev.mysql.com/doc/refman/5.6/en/create-table.html: "The CHECK clause is parsed but ignored by all storage engines."
You can add a check constraint for a column phone:
CREATE TABLE data (
phone varchar(100)
);
DELIMITER $$
CREATE TRIGGER trig_phone_check BEFORE INSERT ON data
FOR EACH ROW
BEGIN
IF (NEW.phone REGEXP '^(\\+?[0-9]{1,4}-)?[0-9]{3,10}$' ) = 0 THEN
SIGNAL SQLSTATE '12345'
SET MESSAGE_TEXT = 'Wroooong!!!';
END IF;
END$$
DELIMITER ;
INSERT INTO data VALUES ('+64-221221442'); -- should be OK
INSERT INTO data VALUES ('+64-22122 WRONG 1442'); -- will fail with the error: #1644 - Wroooong!!!
However you should not rely merely on MySQL (data layer in your case) for data validation. The data should be validated on all levels of your app.
MySQL 8.0.16 (2019-04-25) and MariaDB 10.2.1 (2016-04-18) now not only parse CHECK constraint but also enforces it.
MySQL: https://dev.mysql.com/doc/refman/8.0/en/create-table-check-constraints.html
MariaDB: https://mariadb.com/kb/en/constraint/
Actually, we can can set regular expression within check constraints in MySQL.
Eg.,:
create table fk
(
empid int not null unique,
age int check(age between 18 and 60),
email varchar(20) default 'N/A',
secondary_email varchar(20) check(secondary_email RLIKE'^[a-zA-Z]#[a-zA-Z0-9]\.[a-z,A-Z]{2,4}'),
deptid int check(deptid in(10,20,30))
)
;
This INSERT query will work:
insert into fk values(1,19,'a#a.com','a#b.com', 30);
This INSERT query will not work:
insert into fk values(2,19,'a#a.com','a#bc.com', 30);