The following SQL script works with MySQL 5.16.17 and older, but not with one of my MySQL 5.7.18 installations (the other one, MySQL 5.7.18 launched in a Docker container, is OK as well)
drop table if exists bar;
drop table if exists foo;
create table foo (foo_id int not null primary key, description varchar(32));
insert into foo values ("1", "foo-one");
insert into foo values ("2", "foo-two");
create table bar (bar_id int not null primary key, foo_id int null, description varchar(32), foreign key (foo_id) references foo(foo_id));
insert into bar values ("1", "1", "bar-one");
insert into bar values ("2", "1", "bar-two");
alter table bar change column foo_id foo_id int not null;
The error message is:
Error Code: 1832. Cannot change column 'foo_id': used in a foreign key constraint 'bar_ibfk_1'
The problems seems to be changing a column with a foreign key constraint from NULL to NOT NULL.
I know I could just wrap the last statement in a "SET foreign_key_checks..." call, but I am be interested in whether there are any system variables or configuration settings that influence the behavior of MySQL in this case, because I cannot explain the different behavior between two 5.7.18 instances.
It is not required. A foreign key attribute without NOT NULL can contain NULL values, and this can be used to indicate that no such tuple in the referenced relation is applicable.
To enforce NOT NULL for a column in MySQL, you use the ALTER TABLE .... MODIFY command and restate the column definition, adding the NOT NULL attribute.
The FOREIGN KEY Constraint is a column or list of columns which points to the PRIMARY KEY of another table. you cannot simply update either child or parent table information in a Foreign Key relationship and that's the the purpose of it. If you want to update them, you have to enable, Update CASCADE on Parent table.
Here is the syntax to allow NULL value. alter table yourTableName modify column yourColumnName datatype; Apply the above syntax to modify the column to allow NULL.
you can set FOREIGN_KEY_CHECKS to zero
SET FOREIGN_KEY_CHECKS = 0;
alter table bar change column foo_id foo_id int not null;
SET FOREIGN_KEY_CHECKS = 1;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With