You are looking for the CHECK
SQL operator. Unfortunately, this one is not supported by any of the MySQL engines.
There is a workaround, though, by making use of SQL triggers. You may find more information at CHECK constraint in MySQL is not working and http://dev.mysql.com/doc/refman/5.7/en/create-trigger.html
So, for me (MySQL 5.5+ required), the following snipplet worked:
use test;
CREATE TABLE user (
`user_id` INT NOT NULL,
`username` VARCHAR(50) NULL,
PRIMARY KEY (`id`)
);
delimiter //
create trigger trg_trigger_test_ins before insert on user
for each row
begin
if new.username REGEXP '^[0-9]*$' then
signal sqlstate '45000' set message_text = 'Invalid username containing only digits';
end if;
end
//
delimiter ;
insert into user values(1, '1234');
The last INSERT
statement raised an Error Code: 1644. Invalid username containing only digits
whilst
insert into `test`.`user` values(1, 'a1234');
was inserted properly.
NB: Some kudos also to Throw an error in a MySQL trigger on the signal
idea.
Note that this example only protects against INSERT
s. If you want to be safe, you also need to implement a trigger on UPDATE
.