0

I'm trying to constrict a column to specific values, with no luck.
Here's what I have been trying:

mysql> CREATE TABLE my_table (
    -> name VARCHAR(20),
    -> sex CHAR(1) CHECK (sex IN('F','M'))
    -> );
Query OK, 0 rows affected (0.18 sec)

mysql> INSERT INTO my_table VALUES
    -> ('John','D');
Query OK, 1 row affected (0.07 sec)

mysql> SELECT * FROM my_table;
+------+------+
| name | sex  |
+------+------+
| John | D    |
+------+------+
1 row in set (0.00 sec)

mysql> 

as you can see, the constraint was not enforced...

viggity
  • 15,039
  • 7
  • 88
  • 96
so.very.tired
  • 2,958
  • 4
  • 41
  • 69

3 Answers3

2

This is because the CHECK clause is parsed but ignored by all storage engines.

You can create a trigger for that to check the value of Sex column before insert begins.

Try like this:

DELIMITER $$
CREATE TRIGGER `mytrigger` BEFORE INSERT ON `Table`
FOR EACH ROW
BEGIN
    IF SEX <> 'M' or SEX <> 'F' THEN
    SIGNAL SQLSTATE '123'
        SET MESSAGE_TEXT := 'check constraint on Table.Sex failed';
    END IF;
END$$   
DELIMITER ; 
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
0

You can do this without a trigger by using a foreign key constraint:

CREATE TABLE sexes (
  sex char(1) not null primary key
);

INSERT INTO sexes(sex)
    select 'F' union all select 'M';

CREATE TABLE my_table (
  name VARCHAR(20),
  sex CHAR(1) not null references sexes(sex)
);

There may be other reasons why you would want a code table as well. For instance, you might want to store the full name of the code.

Another approach in MySQL is to use an enumerated type for the values.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

Replace your check constraint with a referential constraint. Add a referential constraint to some table that has a row for male and a row for female. You get one bonus with this method. You can at a later date add more genders to handle cases like earth worms.

CREATE TABLE your_table
(
name varchar(20),
gender char(1),
CONSTRAINT fk_sez FOREIGN KEY (gender)
REFERENCES sezs(gender)
)

Here's a google search for foreign key constraints tutorial

danny117
  • 5,581
  • 1
  • 26
  • 35