Reputation: 423
I have curious about why some not null column already set default value, but during insert sql script, it will throw error.
Here is the sample table
drop table if exists `delivery`;
create table `delivery`(
`price` BIGINT not null default 0,
`created_time` TIMESTAMP(6) not null default CURRENT_TIMESTAMP (6)
) ENGINE=INNODB DEFAULT CHARSET=UTF8MB4
;
Let's say, execute the three statement below, only the second statement will not throw error
insert into `delivery` (`price`,`created_time`) values (null, null);
insert into `delivery` (`price`,`created_time`) values (1, null);
insert into `delivery` (`price`,`created_time`) values (null, now());
So does it have anyway to insert null for bigint datatype column and make it execute success? And any ideas for the logic behind.
Upvotes: 5
Views: 2857
Reputation: 48770
You can't insert null values since you have NOT NULL
constraints on the columns.
The first and third statement throw an error since you are trying to insert a null value into the column price
and/or created_time
, and that clearly doesn't satisfy the constraint(s).
If you really want to allow null values, then remove the NOT NULL
constraint on the column(s).
Alternatively, you could sucessfully run your SQL statements as shown below:
insert into `delivery` () values ();
insert into `delivery` (`price`) values (1);
insert into `delivery` (`created_time`) values (now());
select * from `delivery`;
Result:
price created_time
----- --------------------------
0 2020-04-16 09:48:23.505147
1 2020-04-16 09:48:25.549202
0 2020-04-16 09:48:26.0
EDIT:
The second query actually succeeds in MySQL 5.7; it silently ignores the explicit null value and uses the default value.
It seems that the behavior was fixed in MySQL 8.x since it fails now (as it should).
Upvotes: 2