Related
I have two tables, table1 is the parent table with a column ID and table2 with a column IDFromTable1 (not the actual name) when I put a FK on IDFromTable1 to ID in table1 I get the error Foreign key constraint is incorrectly formed error. I would like to delete table 2 record if table1 record gets deleted. Thanks for any help
ALTER TABLE `table2`
ADD CONSTRAINT `FK1`
FOREIGN KEY (`IDFromTable1`) REFERENCES `table1` (`ID`)
ON UPDATE CASCADE
ON DELETE CASCADE;
Let me know if any other information is needed. I am new to mysql
I ran into this same problem with HeidiSQL. The error you receive is very cryptic. My problem ended up being that the foreign key column and the referencing column were not of the same type or length.
The foreign key column was SMALLINT(5) UNSIGNED and the referenced column was INT(10) UNSIGNED. Once I made them both the same exact type, the foreign key creation worked perfectly.
For anyone facing this problem, just run
SHOW ENGINE INNODB STATUS
and see the LATEST FOREIGN KEY ERROR section for details.
I had the same problem when the parent table was created using MyISAM engine. It's a silly mistake, which I fixed with:
ALTER TABLE parent_table ENGINE=InnoDB;
make sure columns are identical(of same type) and if reference column is not primary_key, make sure it is INDEXED.
Syntax for defining foreign keys is very forgiving, but for anyone else tripping up on this, the fact that foreign keys must be "of the same type" applies even to collation, not just data type and length and bit signing.
Not that you'd mix collation in your model (would you?) but if you do, be sure your primary and foreign key fields are of the same collation type in phpmyadmin or Heidi SQL or whatever you use.
Hope this saves you the four hours of trial and error it cost me.
I had same problem, but solved it.
Just make sure that column 'ID' in 'table1' has UNIQUE index!
And of course the type, length of columns 'ID' and 'IDFromTable1' in these two tables has to be same. But you already know about this.
mysql error texts doesn't help so much, in my case, the column had "not null" constraint, so the "on delete set null" was not allowed
Just for completion.
This error might be as well the case if you have a foreign key with VARCHAR(..) and the charset of the referenced table is different from the table referencing it.
e.g. VARCHAR(50) in a Latin1 Table is different than the VARCHAR(50) in a UTF8 Table.
One more probable cause for the display of this error. The order in which I was creating tables was wrong. I was trying to reference a key from a table that was not yet created.
I had the same issue, both columns were INT(11) NOT NULL but I wan't able to create the foreign key.
I had to disable foreign keys checks to run it successfully :
SET FOREIGN_KEY_CHECKS=OFF;
ALTER TABLE ... ADD CONSTRAINT ...
SET FOREIGN_KEY_CHECKS=ON;
Hope this helps someone.
if everything is ok, just add ->unsigned(); at the end of foregin key.
if it does not work, check the datatype of both fields. they must be the same.
(Last Resent) Even if the field name and data type is the same but the collation is not the same, it will also result to that problem.
For Example
TBL
NAME | DATA
TYPE |
COLLATION
ActivityID | INT |
latin1_general_ci
ActivityID | INT |
utf8_general_ci
Try Changing it into
TBL
NAME | DATA
TYPE |
COLLATION
ActivityID | INT |
latin1_general_ci
ActivityID | INT |
latin1_general_ci
....
This worked for me.
This problem also occur in Laravel when you have the foreign key table table1 migration after the migration in which you reference it table2.
You have to preserve the order of the migration in order to foreign key feature to work properly.
database/migrations/2020_01_01_00001_create_table2_table.php
database/migrations/2020_01_01_00002_create_table1_table.php
should be:
database/migrations/2020_01_01_00001_create_table1_table.php
database/migrations/2020_01_01_00002_create_table2_table.php
Check the tables engine, both tables have to be the same engine, that helped me so much.
Although the other answers are quite helpful, just wanted to share my experience as well.
I faced the issue when I had deleted a table whose id was already being referenced as foreign key in other tables (with data) and tried to recreate/import the table with some additional columns.
The query for recreation (generated in phpMyAdmin) looked like the following:
CREATE TABLE `the_table` (
`id` int(11) NOT NULL, /* No PRIMARY KEY index */
`name` varchar(255) NOT NULL,
`name_fa` varchar(255) NOT NULL,
`name_pa` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
... /* SOME DATA DUMP OPERATION */
ALTER TABLE `the_table`
ADD PRIMARY KEY (`id`), /* PRIMARY KEY INDEX */
ADD UNIQUE KEY `uk_acu_donor_name` (`name`);
As you may notice, the PRIMARY KEY index was set after the creation (and insertion of data) which was causing the problem.
Solution
The solution was to add the PRIMARY KEY index on table definition query for the id which was being referenced as foreign key, while also removing it from the ALTER TABLE part where indexes were being set:
CREATE TABLE `the_table` (
`id` int(11) NOT NULL PRIMARY KEY, /* <<== PRIMARY KEY INDEX ON CREATION */
`name` varchar(255) NOT NULL,
`name_fa` varchar(255) NOT NULL,
`name_pa` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Try running following:
show create table Parent
//and check if type for both tables are the same, like myISAM or innoDB, etc
//Other aspects to check with this error message: the columns used as foreign
keys must be indexed, they must be of the same type
(if i.e one is of type smallint(5) and the other of type smallint(6),
it won't work), and, if they are integers, they should be unsigned.
//or check for charsets
show variables like "character_set_database";
show variables like "collation_database";
//edited: try something like this
ALTER TABLE table2
ADD CONSTRAINT fk_IdTable2
FOREIGN KEY (Table1_Id)
REFERENCES Table1(Table1_Id)
ON UPDATE CASCADE
ON DELETE CASCADE;
I lost for hours for that!
PK in one table was utf8 in other was utf8_unicode_ci!
thanks S Doerin:
"Just for completion.
This error might be as well the case if you have a foreign key with VARCHAR(..) and the charset of the referenced table is different from the table referencing it.
e.g. VARCHAR(50) in a Latin1 Table is different than the VARCHAR(50) in a UTF8 Table."
i solved this problem, changing the type of characters of the table.
the creation have latin1 and the correct is utf8.
add the next line.
DEFAULT CHARACTER SET = utf8;
I had the same problems.
The issue is the reference column is not a primary key.
Make it a primary key and problem is solved.
My case was that I had a typo on the referred column:
MariaDB [blog]> alter table t_user add FOREIGN KEY ( country_code ) REFERENCES t_country ( coutry_code );
ERROR 1005 (HY000): Can't create table `blog`.`t_user` (errno: 150 "Foreign key constraint is incorrectly formed")
The error message is quite cryptic and I've tried everything - verifying the types of the columns, collations, engines, etc.
It took me awhile to note the typo and after fixing it all worked fine:
MariaDB [blog]> alter table t_user add FOREIGN KEY ( country_code ) REFERENCES t_country ( country_code );
Query OK, 2 rows affected (0.039 sec)
Records: 2 Duplicates: 0 Warnings: 0
I face this problem the error came when you put the primary key in different data type like:
table 1:
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('product_name');
});
table 2:
Schema::create('brands', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('brand_name');
});
the data type for id of the second table must be increments
For anyone struggling as I was with this issue, this was my problem:
I was trying to alter a table to change a field from VARCHAR(16) to VARCHAR(255) and this was referencing another table column where the datatype was still VARCHAR(16)...
I had the same issue with Symfony 2.8.
I didn't get it at first, because there were no similar problems with int length of foreign keys etc.
Finally I had to do the following in the project folder. (A server restart didn't help!)
app/console doctrine:cache:clear-metadata
app/console doctrine:cache:clear-query
app/console doctrine:cache:clear-result
I was using HeidiSQL and to solve this problem I had to create an index in the referenced table with all the columns being referenced.
I had issues using Alter table to add a foreign key between two tables and the thing that helped me was making sure each column that I was trying to add a foreign key relationship to was indexed. To do this in PHP myAdmin:
Go to the table and click on the structure tab.
Click the index option to index the desired column as shown in screenshot:
Once I indexed both columns I was trying to reference with my foreign keys, I was able to successfully use the alter table and create the foreign key relationship. You will see that the columns are indexed like in the below screenshot:
notice how zip_code shows up in both tables.
I ran into the same issue just now. In my case, all I had to do is to make sure that the table I am referencing in the foreign key must be created prior to the current table (earlier in the code). So if you are referencing a variable (x*5) the system should know what x is (x must be declared in earlier lines of code). This resolved my issue, hope it'll help someone else.
The problem is very simple to solve
e.g: you have two table with names users and posts and you want create foreign key in posts table and you use phpMyAdmin
1) in post table add new column
(name:use_id | type: like the id in user table | Length:like the id in user table | Default:NULL | Attributes:unsigned | index:INDEX )
2)on Structure tab go to relation view
(Constraint name: auto set by phpmyAdmin | column name:select user_id |table:users | key: id ,...)
It was simply solved
javad mosavi iran/urmia
I had the same error, and I discovered that on my own case, one table was MyISAM, and the other one INNO. Once I switched the MyISAM table to INNO. It solved the issue.
One more solution which I was missing here is, that each primary key of the referenced table should have an entry with a foreign key in the table where the constraint is created.
If U Table Is Myisum And New Table Is InoDb you Are Note Foreign
You Must Change MyIsum Table To InoDb
I'm beginning with MySQL, trying to set up a 2-columns primary key, I'm using phpmyadmin.
I managed to somehow mark two columns as a primary key (this is what i have right now, the primary columns are underligned) but they seem to act as two separate primary key, I can't add rows with the same ID and different region, or reversibly the same region and different ID.
What should i fix ? thanks !
If you run SHOW CREATE TABLE you will most likely see the following:
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
region VARCHAR,
....
PRIMARY KEY (id),
UNIQUE KEY somename (id,region)
So what has been created for you is a unique key. A unique key can be used as primary key, but you will have to get rid of your other primary key id.
This can be done by:
ALTER TABLE your_table_name DROP PRIMARY KEY;
Since I do not know all your specs, test the result and see if all the desired behavior is still in place.
I have two tables as follow:
1st Table:
CREATE TABLE User (
User_ID VARCHAR(8)NOT NULL PRIMARY KEY,
User_Name VARCHAR (25) NOT NULL,
User_Gender CHAR (1) NOT NULL,
User_Position VARCHAR (10) NOT NULL,
);
2nd table:
CREATE TABLE Training (
Training_Code VARCHAR(8) NOT NULL Primary Key,
Training_Title VARCHAR(30) NOT NULL,
);
I am trying to create a table which has two foreign keys to join both of the previous tables:
CREATE TABLE Request (
User_ID VARCHAR(8) NOT NULL,
Training_Code VARCHAR(8) NOT NULL,
Request_Status INT(1) NOT NULL
);
When I am trying to set the foreign keys in the new table, the User_ID can be done successfully but the Training_Code cannot be set to foreign key due to the error:
ERROR 1215 (HY000): Cannot add foreign key constraint
As I searched for this problem, the reason for it, is that data type is not the same, or name is not the same.. but in my situation both are correct so could you tell me what is wrong here ?
You need an index for this column in table Request too:
Issue first
CREATE INDEX idx_training_code ON Request (Training_Code);
Then you should be successful creating the foreign key constraint with
ALTER TABLE Request
ADD CONSTRAINT FOREIGN KEY idx_training_code (Training_Code)
REFERENCES Training(Training_Code);
It worked for me. But I've got to say that it worked without create index too, as the documentation of Using FOREIGN KEY Constraints states:
MySQL requires indexes on foreign keys and referenced keys so that
foreign key checks can be fast and not require a table scan. In the
referencing table, there must be an index where the foreign key
columns are listed as the first columns in the same order. Such an
index is created on the referencing table automatically if it does not
exist. This index might be silently dropped later, if you create
another index that can be used to enforce the foreign key constraint.
index_name, if given, is used as described previously.
Emphasis by me. I don't know what's the issue in your case.
Demo
Explanation of the issue
The behavior mentioned in the question can be reproduced if the table Training is using the MyISAM storage engine. Then creating a foreign key referencing the table Training will produce the mentioned error.
If there's data in the table, then simple dropping of the table would not be the best solution. You can change the storage engine to InnoDB with
ALTER TABLE Training Engine=InnoDB;
Now you can successfully add the foreign key constraint.
I have two tables, table1 is the parent table with a column ID and table2 with a column IDFromTable1 (not the actual name) when I put a FK on IDFromTable1 to ID in table1 I get the error Foreign key constraint is incorrectly formed error. I would like to delete table 2 record if table1 record gets deleted. Thanks for any help
ALTER TABLE `table2`
ADD CONSTRAINT `FK1`
FOREIGN KEY (`IDFromTable1`) REFERENCES `table1` (`ID`)
ON UPDATE CASCADE
ON DELETE CASCADE;
Let me know if any other information is needed. I am new to mysql
I ran into this same problem with HeidiSQL. The error you receive is very cryptic. My problem ended up being that the foreign key column and the referencing column were not of the same type or length.
The foreign key column was SMALLINT(5) UNSIGNED and the referenced column was INT(10) UNSIGNED. Once I made them both the same exact type, the foreign key creation worked perfectly.
For anyone facing this problem, just run
SHOW ENGINE INNODB STATUS
and see the LATEST FOREIGN KEY ERROR section for details.
I had the same problem when the parent table was created using MyISAM engine. It's a silly mistake, which I fixed with:
ALTER TABLE parent_table ENGINE=InnoDB;
make sure columns are identical(of same type) and if reference column is not primary_key, make sure it is INDEXED.
Syntax for defining foreign keys is very forgiving, but for anyone else tripping up on this, the fact that foreign keys must be "of the same type" applies even to collation, not just data type and length and bit signing.
Not that you'd mix collation in your model (would you?) but if you do, be sure your primary and foreign key fields are of the same collation type in phpmyadmin or Heidi SQL or whatever you use.
Hope this saves you the four hours of trial and error it cost me.
I had same problem, but solved it.
Just make sure that column 'ID' in 'table1' has UNIQUE index!
And of course the type, length of columns 'ID' and 'IDFromTable1' in these two tables has to be same. But you already know about this.
mysql error texts doesn't help so much, in my case, the column had "not null" constraint, so the "on delete set null" was not allowed
Just for completion.
This error might be as well the case if you have a foreign key with VARCHAR(..) and the charset of the referenced table is different from the table referencing it.
e.g. VARCHAR(50) in a Latin1 Table is different than the VARCHAR(50) in a UTF8 Table.
One more probable cause for the display of this error. The order in which I was creating tables was wrong. I was trying to reference a key from a table that was not yet created.
I had the same issue, both columns were INT(11) NOT NULL but I wan't able to create the foreign key.
I had to disable foreign keys checks to run it successfully :
SET FOREIGN_KEY_CHECKS=OFF;
ALTER TABLE ... ADD CONSTRAINT ...
SET FOREIGN_KEY_CHECKS=ON;
Hope this helps someone.
if everything is ok, just add ->unsigned(); at the end of foregin key.
if it does not work, check the datatype of both fields. they must be the same.
(Last Resent) Even if the field name and data type is the same but the collation is not the same, it will also result to that problem.
For Example
TBL
NAME | DATA
TYPE |
COLLATION
ActivityID | INT |
latin1_general_ci
ActivityID | INT |
utf8_general_ci
Try Changing it into
TBL
NAME | DATA
TYPE |
COLLATION
ActivityID | INT |
latin1_general_ci
ActivityID | INT |
latin1_general_ci
....
This worked for me.
This problem also occur in Laravel when you have the foreign key table table1 migration after the migration in which you reference it table2.
You have to preserve the order of the migration in order to foreign key feature to work properly.
database/migrations/2020_01_01_00001_create_table2_table.php
database/migrations/2020_01_01_00002_create_table1_table.php
should be:
database/migrations/2020_01_01_00001_create_table1_table.php
database/migrations/2020_01_01_00002_create_table2_table.php
Check the tables engine, both tables have to be the same engine, that helped me so much.
Although the other answers are quite helpful, just wanted to share my experience as well.
I faced the issue when I had deleted a table whose id was already being referenced as foreign key in other tables (with data) and tried to recreate/import the table with some additional columns.
The query for recreation (generated in phpMyAdmin) looked like the following:
CREATE TABLE `the_table` (
`id` int(11) NOT NULL, /* No PRIMARY KEY index */
`name` varchar(255) NOT NULL,
`name_fa` varchar(255) NOT NULL,
`name_pa` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
... /* SOME DATA DUMP OPERATION */
ALTER TABLE `the_table`
ADD PRIMARY KEY (`id`), /* PRIMARY KEY INDEX */
ADD UNIQUE KEY `uk_acu_donor_name` (`name`);
As you may notice, the PRIMARY KEY index was set after the creation (and insertion of data) which was causing the problem.
Solution
The solution was to add the PRIMARY KEY index on table definition query for the id which was being referenced as foreign key, while also removing it from the ALTER TABLE part where indexes were being set:
CREATE TABLE `the_table` (
`id` int(11) NOT NULL PRIMARY KEY, /* <<== PRIMARY KEY INDEX ON CREATION */
`name` varchar(255) NOT NULL,
`name_fa` varchar(255) NOT NULL,
`name_pa` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Try running following:
show create table Parent
//and check if type for both tables are the same, like myISAM or innoDB, etc
//Other aspects to check with this error message: the columns used as foreign
keys must be indexed, they must be of the same type
(if i.e one is of type smallint(5) and the other of type smallint(6),
it won't work), and, if they are integers, they should be unsigned.
//or check for charsets
show variables like "character_set_database";
show variables like "collation_database";
//edited: try something like this
ALTER TABLE table2
ADD CONSTRAINT fk_IdTable2
FOREIGN KEY (Table1_Id)
REFERENCES Table1(Table1_Id)
ON UPDATE CASCADE
ON DELETE CASCADE;
I lost for hours for that!
PK in one table was utf8 in other was utf8_unicode_ci!
thanks S Doerin:
"Just for completion.
This error might be as well the case if you have a foreign key with VARCHAR(..) and the charset of the referenced table is different from the table referencing it.
e.g. VARCHAR(50) in a Latin1 Table is different than the VARCHAR(50) in a UTF8 Table."
i solved this problem, changing the type of characters of the table.
the creation have latin1 and the correct is utf8.
add the next line.
DEFAULT CHARACTER SET = utf8;
I had the same problems.
The issue is the reference column is not a primary key.
Make it a primary key and problem is solved.
My case was that I had a typo on the referred column:
MariaDB [blog]> alter table t_user add FOREIGN KEY ( country_code ) REFERENCES t_country ( coutry_code );
ERROR 1005 (HY000): Can't create table `blog`.`t_user` (errno: 150 "Foreign key constraint is incorrectly formed")
The error message is quite cryptic and I've tried everything - verifying the types of the columns, collations, engines, etc.
It took me awhile to note the typo and after fixing it all worked fine:
MariaDB [blog]> alter table t_user add FOREIGN KEY ( country_code ) REFERENCES t_country ( country_code );
Query OK, 2 rows affected (0.039 sec)
Records: 2 Duplicates: 0 Warnings: 0
I face this problem the error came when you put the primary key in different data type like:
table 1:
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('product_name');
});
table 2:
Schema::create('brands', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('brand_name');
});
the data type for id of the second table must be increments
For anyone struggling as I was with this issue, this was my problem:
I was trying to alter a table to change a field from VARCHAR(16) to VARCHAR(255) and this was referencing another table column where the datatype was still VARCHAR(16)...
I had the same issue with Symfony 2.8.
I didn't get it at first, because there were no similar problems with int length of foreign keys etc.
Finally I had to do the following in the project folder. (A server restart didn't help!)
app/console doctrine:cache:clear-metadata
app/console doctrine:cache:clear-query
app/console doctrine:cache:clear-result
I was using HeidiSQL and to solve this problem I had to create an index in the referenced table with all the columns being referenced.
I had issues using Alter table to add a foreign key between two tables and the thing that helped me was making sure each column that I was trying to add a foreign key relationship to was indexed. To do this in PHP myAdmin:
Go to the table and click on the structure tab.
Click the index option to index the desired column as shown in screenshot:
Once I indexed both columns I was trying to reference with my foreign keys, I was able to successfully use the alter table and create the foreign key relationship. You will see that the columns are indexed like in the below screenshot:
notice how zip_code shows up in both tables.
I ran into the same issue just now. In my case, all I had to do is to make sure that the table I am referencing in the foreign key must be created prior to the current table (earlier in the code). So if you are referencing a variable (x*5) the system should know what x is (x must be declared in earlier lines of code). This resolved my issue, hope it'll help someone else.
The problem is very simple to solve
e.g: you have two table with names users and posts and you want create foreign key in posts table and you use phpMyAdmin
1) in post table add new column
(name:use_id | type: like the id in user table | Length:like the id in user table | Default:NULL | Attributes:unsigned | index:INDEX )
2)on Structure tab go to relation view
(Constraint name: auto set by phpmyAdmin | column name:select user_id |table:users | key: id ,...)
It was simply solved
javad mosavi iran/urmia
I had the same error, and I discovered that on my own case, one table was MyISAM, and the other one INNO. Once I switched the MyISAM table to INNO. It solved the issue.
One more solution which I was missing here is, that each primary key of the referenced table should have an entry with a foreign key in the table where the constraint is created.
If U Table Is Myisum And New Table Is InoDb you Are Note Foreign
You Must Change MyIsum Table To InoDb
I want to add another primary key to a table in mysql.
I use phpmyadmin to communicate with mysql server.
When I click the primary icon for the desired field it gives me this error:
#1075 - Incorrect table definition; there can be only one auto column and it must be defined as a key
Edited:
here's the query:
ALTER TABLE `files` DROP PRIMARY KEY ,ADD PRIMARY KEY ( `file_type` )
How can I do it?
As the name "primary" key says, there may be only one of that (ref: Highlander).
What you might want to try is a UNIQUE KEY, that acts just like a primary for most purpouses. Auto_increment doesn't seem to fulfill any purpouse if used a second time - what'ts the point of two fields carrying exactly the same information?
I believe in your case, what you need is a composite key. I do not know your table structure, but here is a general example taken from here,
CREATE TABLE track(
album CHAR(10),
disk INTEGER,
posn INTEGER,
song VARCHAR(255),
PRIMARY KEY (album, disk, posn)
)
In this case, there is a combination of 3 columns which avoid the duplicate records as you require. Please let me know if I have any mistakes in understanding your scenario.
The error message says it, I think:
the auto_increment column must be key.
So use this query first:
ALTER TABLE 'files' CHANGE 'id' 'id' INT( 10 ) UNSIGNED NOT NULL;
this will remove the auto_increment.
Also, I recommend the Uniqe key as suggested by other answer. I believe there should always (almost) be an Id column in each table.
We can Give Primary Key only once for a table. You can prefer UNIQUE KEY to prevent duplicate records
ALTER TABLE Persons
ADD UNIQUE (P_Id)
You can mark all the fields you want as primary keys, including the existing one. The system internally will drop the existing one and will set all you marked.