Search code examples
mysqlsqldatabasemysql-error-1064

insert not working on mysql 5.7.12-0?


my table structure is

  CREATE TABLE IF NOT EXISTS `emp` (
 `id` int(3) NOT NULL AUTO_INCREMENT,
 `name` varchar(11) DEFAULT NULL,
 `age` varchar(31) NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

My query is :

 INSERT INTO `emp` (`id`, `name`) VALUES ('1', 'prashant');

This is working with all the MYSQL versions below 5.7, but not working with MYSQL version 5.7.12-0ubuntu1

Getting error :

#1364 - Field 'age' doesn't have a default value

What is new in this version ??

Try it on mysql version below 5.7 ,you will see the difference.

Thanks :-)


Solution

  • It would be a huge surprise if this worked in any version of mysql at all. Copy paste this into sqlfiddle.com (mysql 5.6 or 5.5) and confirm for yourself.

    age is defined as varchar(31) and not null. Thus your insert statement should have a value for that column. Or you should give it a default value. While you are at it, change it to a more appropriate data type.

     CREATE TABLE IF NOT EXISTS `emp` (
     `id` int(3) NOT NULL AUTO_INCREMENT,
     `name` varchar(11) DEFAULT NULL,
     `age` int(3) NOT NULL default 0,
     PRIMARY KEY (`id`)
    ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
    

    Updated:

    Thinking about this some more I think you have switched off Strict Mode in your older version of mysql

    Strict mode controls how MySQL handles invalid or missing values in data-change statements such as INSERT or UPDATE. A value can be invalid for several reasons. For example, it might have the wrong data type for the column, or it might be out of range. A value is missing when a new row to be inserted does not contain a value for a non-NULL column that has no explicit DEFAULT clause in its definition. (For a NULL column, NULL is inserted if the value is missing.) Strict mode also affects DDL statements such as CREATE TABLE.

    So my original statement is wrong! With string mode off, the default for varchar is probably '' (not sure though never used strict mode off)