Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

CHECK constraint with multiple conditions MySQL

CREATE TABLE shoesize( 
nr TINYINT NOT NULL,
shoesize VARCHAR(6) NOT NULL,

CHECK (shoesize = 'mini' OR 'medium' OR 'maxi'),
PRIMARY KEY (nr)
)engine=innodb;


insert into shoesize(nr,shoesize) values ('1','mini');
insert into shoesize(nr,shoesize) values ('2','medium');
insert into shoesize(nr,shoesize) values ('3','maxi');
insert into shoesize(nr,shoesize) values ('4','ultra');
insert into shoesize(nr,shoesize) values ('5','mega');

    Error Code: 3819. Check constraint 'shoesize_chk_1' is violated.    0.015 sec

I’m trying to make a constraint, that says only shoes where a certain text is accepted. However the constraint fires when I try to enter data. It should be possible to have an OR in the check as far as I’m concerned?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Your problem is that only the first value mini is cheked, but you need to repeat the equation to get also the rest

CREATE TABLE shoesize( 
nr TINYINT NOT NULL,
shoesize VARCHAR(6) NOT NULL,

CHECK (shoesize = 'mini' OR  shoesize =  'medium' OR shoesize = 'maxi'),
PRIMARY KEY (nr)
)engine=innodb;


insert into shoesize(nr,shoesize) values ('1','mini');
insert into shoesize(nr,shoesize) values ('2','medium');
insert into shoesize(nr,shoesize) values ('3','maxi');
insert into shoesize(nr,shoesize) values ('4','ultra');
insert into shoesize(nr,shoesize) values ('5','mega');



SELECT * FROM shoesize
nr shoesize
1 mini
2 medium
3 maxi

fiddle

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading