Question

I am using MySQL client of version 5.5. Today I tried "NOT NULL" to set an attribute, only find it doesn't work during my test. Anybody helps explain this?

    //Create Table
    CREATE TABLE state(
           state_cd  char(2) NOT NULL,
           state_name varchar(30)
           );

    //Insert an "Invalid" Record
    INSERT INTO state(state_name)
           values('Massachusetts');

    //DB Operation succeeds!!!
    Query OK, 1 row affected, 1 warning (0.09 sec)

    //Check the table
    mysql> select * from state;
    +----------+---------------+
    | state_cd | state_name    |
    +----------+---------------+
    |          | Massachusetts |
    +----------+---------------+
    1 row in set (0.00 sec)


    mysql> describe state;
    +------------+-------------+------+-----+---------+-------+
    | Field      | Type        | Null | Key | Default | Extra |
    +------------+-------------+------+-----+---------+-------+
    | state_cd   | char(2)     | NO   |     | NULL    |       |
    | state_name | varchar(30) | YES  |     | NULL    |       |
    +------------+-------------+------+-----+---------+-------+
    2 rows in set (0.00 sec)
Was it helpful?

Solution

If you try to insert or update a NOT NULL column to NULL, MySQL will set it to the default instead (in this case the de-facto default is empty string). MySQL will also issue a warning that you can see with SHOW WARNINGS that should say something about an incorrect column value. It will not prevent you from attempting to insert a null value, but it will not accept the value.

You may want to specify an explicit default value

state_cd char(2) NOT NULL DEFAULT '--'

If you want the query to fail when attempting you can either handle this at the application level or take a look at MySQL server modes, which you can set to TRADITIONAL so INSERT/UPDATE will fail when attempting to add an incorrect value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top