mysql error 150 with INNODB [duplicate] - mysql

I am trying to import a .sql file and its failing on creating tables.
Here's the query that fails:
CREATE TABLE `data` (
`id` int(10) unsigned NOT NULL,
`name` varchar(100) NOT NULL,
`value` varchar(15) NOT NULL,
UNIQUE KEY `id` (`id`,`name`),
CONSTRAINT `data_ibfk_1` FOREIGN KEY (`id`) REFERENCES `keywords` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
I exported the .sql from the same database, I dropped all the tables and now im trying to import it, why is it failing?
MySQL: Can't create table './dbname/data.frm' (errno: 150)

From the MySQL - FOREIGN KEY Constraints Documentation:
If you re-create a table that was dropped, it must have a definition that conforms to the foreign key constraints referencing it. It must have the correct column names and types, and it must have indexes on the referenced keys, as stated earlier. If these are not satisfied, MySQL returns Error 1005 and refers to Error 150 in the error message, which means that a foreign key constraint was not correctly formed. Similarly, if an ALTER TABLE fails due to Error 150, this means that a foreign key definition would be incorrectly formed for the altered table.

Error 150 means you have a problem with your foreign key. Possibly the key on the foreign table isn't the exact same type?

You can get the actual error message by running SHOW ENGINE INNODB STATUS; and then looking for LATEST FOREIGN KEY ERROR in the output.
Source: answer from another user in a similar question

Data types must match exactly. If you are dealing with varchar types, the tables must use the same collation.

I think all these answers while correct are misleading to the question.
The actual answer is this before you start a restore, if you're restoring a dump file with foreign keys:
SET FOREIGN_KEY_CHECKS=0;
because naturally the restore will be creating some constraints before the foreign table even exists.

In some cases, you may encounter this error message if there are different engines between the relating tables. For example, a table may be using InnoDB while the other uses MyISAM. Both need to be same

Error no. 150 means a foreign key constraint failure. You are probably creating this table before the table the foreign key depends on (table keywords). Create that table first and it should work fine.
If it doesn't, remove the foreign key statement and add it after the table is created - you will get a more meaningful error message about the specific constraint failure.

There are quite a few things that can cause errno 150, so for people searching this topic, here is what I think is a close to exhaustive list (source Causes of Errno 150):
For errno 150 or errno 121, simply typing in SHOW ENGINE INNODB STATUS, there is a section called "LATEST FOREIGN KEY ERROR". Under that it will give you a very helpful error message, which typically will tell you right away what is the matter. You need SUPER privileges to run it, so if you don't have that, you'll just have to test out the following scenarios.
1) Data Types Don't Match: The types of the columns have to be the same
2) Parent Columns Not Indexed (Or Indexed in Wrong Order)
3) Column Collations Don't Match
4) Using SET NULL on a NOT NULL Column
5) Table Collations Don't Match: even if the column collations match, on some MySQL versions this can be a problem.
6) Parent Column Doesn't Actually Exist In Parent Table. Check spelling (and perhaps a space at the beginning or end of column)
7) One of the indexes on one of the columns is incomplete, or the column is too long for a complete index. Note that MySQL (unless you tweak it) has a maximum single column key length of 767 bytes (this corresponds to a varchar(255) UTF column)
In case you get an errno 121, here are a couple of causes:
1) The constraint name you chose is already taken
2) On some systems if there is a case difference in your statement and table names. This can bite you if you go from one server to another that have different case handling rules.

Sometimes MySQL is just super stupid - i can understand the reason cause of foreign-keys.. but in my case, i have just dropped the whole database, and i still get the error... why? i mean, there is no database anymore... and the sql-user i'm using has no access to any other db's on the server... i mean, the server is "empty" for the current user and i still get this error? Sorry but i guess MySQL is lying to me... but i can deal with it :) Just add these two lines of SQL around your fucky statement:
SET FOREIGN_KEY_CHECKS = 0;
# some code that gives you errno: 150
SET FOREIGN_KEY_CHECKS = 1;
Now the sql should be executed... If you really have a foreign-key problem, it would show up to you by the line where you will enable the checks again - this will fail then.. but my server is just quiet :)

usually, the mismatch between foreign key & primary key causes the
error:150.
The foreign key must have the same datatype as the primary key. Also, if the primary key is unsigned then the foreign key must also be unsigned.

I had same issue. It was related to table's column Collation and Character Set.
Make sure Character Set and Collation must be same for both columns on two tables. If you want to set a foreign key on that.
Example- If you put foreign key on userID column of userImage table referencing userID column of users table.Then Collation must be same that is utf8_general_ci and Character set utf8 for both columns of tables. Generally when you create a table mysql takes these two configuration from server settings.

After cruising through the answers above, and experimenting a bit, this is an effective way to solve Foreign Key errors in MySQL (1005 - error 150).
For the foreign key to be properly created, all MySQL asks for is:
All referenced keys MUST have either PRIMARY or UNIQUE index.
Referencing Column again MUST have identical data type to the Referenced column.
Satisfy these requirements and all will be well.

I experienced this error when have ported Windows application to Linux. In Windows, database table names are case-insensitive, and in Linux they are case-sensitive, probably because of file system difference. So, on Windows table Table1 is the same as table1, and in REFERENCES both table1 and Table1 works. On Linux, when application used table1 instead of Table1 when it created database structure I saw error #150; when I made correct character case in Table1 references, it started to work on Linux too. So, if nothing else helps, make you sure that in REFERENCES you use correct character case in table name when you on Linux.

Change the engines of your tables, only innoDB supports foreign keys

If the PK table is created in one CHARSET and then you create FK table in another CHARSET..then also you might get this error...I too got this error but after changing the charset to PK charset then it got executed without errors
create table users
(
------------
-------------
)DEFAULT CHARSET=latin1;
create table Emp
(
---------
---------
---------
FOREIGN KEY (userid) REFERENCES users(id) on update cascade on delete cascade)ENGINE=InnoDB, DEFAULT CHARSET=latin1;

This error can occur if two tables have a reference, for example, one table is Student and another table is Education, and we want the Education table to have a foreign key reference of Student table. In this instance the column data type for both tables should be same, otherwise it will generate an error.

In most of the cases the problem is because of the ENGINE dIfference .If the parent is created by InnoDB then the referenced tables supposed to be created by MyISAM & vice versa

In my case. I had problems with engine and charset because my Hosting server change settings and my new tables was MyISAM but my old tables are InnoDB. Just i changed.

Please make sure both your primary key column and referenced column have the same data types and attributes (unsigned, binary, unsigned zerofill etc).

A real edge case is where you have used an MySQL tool, (Sequel Pro in my case) to rename a database. Then created a database with the same name.
This kept foreign key constraints to the same database name, so the renamed database (e.g. my_db_renamed) had foreign key constraints in the newly created database (my_db)
Not sure if this is a bug in Sequel Pro, or if some use case requires this behaviour, but it cost me best part of a morning :/

The column of PARENT table to which you are referring to from child table has to be unique. If it is not, cause an error no 150.

I had the same error. In my case the reason for the error was that I had a ON DELETE SET NULL statement in the constraint while the field on which I put the constraint in its definition had a NOT NULL statement. Allowing NULL in the field solved the problem.

I faced this kind of issue while creating DB from the textfile.
mysql -uroot -padmin < E:\important\sampdb\createdb.sql
mysql -uroot -padmin sampdb < E:\important\sampdb\create_student.sql
mysql -uroot -padmin sampdb < E:\important\sampdb\create_absence.sql
mysql -uroot -padmin sampdb < E:\important\sampdb\insert_student.sql
mysql -uroot -padmin sampdb < E:\important\sampdb\insert_absence.sql
mysql -uroot -padmin sampdb < E:\important\sampdb\load_student.sql
mysql -uroot -padmin sampdb < E:\important\sampdb\load_absence.sql
I just wrote the above lines in Create.batand run the bat file.
My mistake is in the sequence order of execution in my sql files. I tried to create table with primary key and also foreign key. While its running it will search for the reference table but tables are not there.
So it will return those kind of error.
If you creating tables with foreign key then check the reference
tables were present or not. And also check the name of the reference
tables and fields.

I had a similar problem but mine was because i was adding a new field to an existing table that had data , and the new field was referencing another field from the parent table and also had the Defination of NOT NULL and without any DEFAULT VALUES. - I found out the reason things were not working was because
My new field needed to autofill the blank fields with a value from the parent table on each record, before the constraint could be applied. Every time the constraint is applied it needs to leave the Integrity of the table data intact. Implementing the Constraint (Foreign Key) yet there were some database records that did not have the values from the parent table would mean the data is corrupt so MySQL would NEVER ENFORCE YOUR CONSTRAINT
It is important to remember that under normal circumstances if you planned your database well ahead of time, and implemented constraints before data insertion this particular scenario would be avoided
The easier Approach to avoid this gotcha is to
Save your database tables data
Truncate the table data (and table artifacts i.e indexes etc)
Apply the Constraints
Import Your Data
I Hope this helps someone

Create the table without foreign key, then set the foreign key separately.

Perhaps this will help? The definition of the primary key column should be exactly the same as the foreign key column.

Make sure that the all tables can support foreign key - InnoDB engine

I had a similar problem when dumping a Django mysql database with a single table. I was able to fix the problem by dumping the database to a text file, moving the table in question to the end of the file using emacs and importing the modified sql dump file into the new instance.
HTH Uwe

I've corrected the problem by making the variable accept null
ALTER TABLE `ajout_norme`
CHANGE `type_norme_code` `type_norme_code` VARCHAR( 2 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL

I got the same problem when executing a series of MySQL commands. Mine occurs during creating a table when referencing a foreign key to other table which was not created yet. It's the sequence of table existence before referencing.
The solution: Create the parent tables first before creating a child table which has a foreign key.

Related

1005, "Can't create table 'test.addr_count' (errno: 150)" [duplicate]

I am trying to import a .sql file and its failing on creating tables.
Here's the query that fails:
CREATE TABLE `data` (
`id` int(10) unsigned NOT NULL,
`name` varchar(100) NOT NULL,
`value` varchar(15) NOT NULL,
UNIQUE KEY `id` (`id`,`name`),
CONSTRAINT `data_ibfk_1` FOREIGN KEY (`id`) REFERENCES `keywords` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
I exported the .sql from the same database, I dropped all the tables and now im trying to import it, why is it failing?
MySQL: Can't create table './dbname/data.frm' (errno: 150)
From the MySQL - FOREIGN KEY Constraints Documentation:
If you re-create a table that was dropped, it must have a definition that conforms to the foreign key constraints referencing it. It must have the correct column names and types, and it must have indexes on the referenced keys, as stated earlier. If these are not satisfied, MySQL returns Error 1005 and refers to Error 150 in the error message, which means that a foreign key constraint was not correctly formed. Similarly, if an ALTER TABLE fails due to Error 150, this means that a foreign key definition would be incorrectly formed for the altered table.
Error 150 means you have a problem with your foreign key. Possibly the key on the foreign table isn't the exact same type?
You can get the actual error message by running SHOW ENGINE INNODB STATUS; and then looking for LATEST FOREIGN KEY ERROR in the output.
Source: answer from another user in a similar question
Data types must match exactly. If you are dealing with varchar types, the tables must use the same collation.
I think all these answers while correct are misleading to the question.
The actual answer is this before you start a restore, if you're restoring a dump file with foreign keys:
SET FOREIGN_KEY_CHECKS=0;
because naturally the restore will be creating some constraints before the foreign table even exists.
In some cases, you may encounter this error message if there are different engines between the relating tables. For example, a table may be using InnoDB while the other uses MyISAM. Both need to be same
Error no. 150 means a foreign key constraint failure. You are probably creating this table before the table the foreign key depends on (table keywords). Create that table first and it should work fine.
If it doesn't, remove the foreign key statement and add it after the table is created - you will get a more meaningful error message about the specific constraint failure.
There are quite a few things that can cause errno 150, so for people searching this topic, here is what I think is a close to exhaustive list (source Causes of Errno 150):
For errno 150 or errno 121, simply typing in SHOW ENGINE INNODB STATUS, there is a section called "LATEST FOREIGN KEY ERROR". Under that it will give you a very helpful error message, which typically will tell you right away what is the matter. You need SUPER privileges to run it, so if you don't have that, you'll just have to test out the following scenarios.
1) Data Types Don't Match: The types of the columns have to be the same
2) Parent Columns Not Indexed (Or Indexed in Wrong Order)
3) Column Collations Don't Match
4) Using SET NULL on a NOT NULL Column
5) Table Collations Don't Match: even if the column collations match, on some MySQL versions this can be a problem.
6) Parent Column Doesn't Actually Exist In Parent Table. Check spelling (and perhaps a space at the beginning or end of column)
7) One of the indexes on one of the columns is incomplete, or the column is too long for a complete index. Note that MySQL (unless you tweak it) has a maximum single column key length of 767 bytes (this corresponds to a varchar(255) UTF column)
In case you get an errno 121, here are a couple of causes:
1) The constraint name you chose is already taken
2) On some systems if there is a case difference in your statement and table names. This can bite you if you go from one server to another that have different case handling rules.
Sometimes MySQL is just super stupid - i can understand the reason cause of foreign-keys.. but in my case, i have just dropped the whole database, and i still get the error... why? i mean, there is no database anymore... and the sql-user i'm using has no access to any other db's on the server... i mean, the server is "empty" for the current user and i still get this error? Sorry but i guess MySQL is lying to me... but i can deal with it :) Just add these two lines of SQL around your fucky statement:
SET FOREIGN_KEY_CHECKS = 0;
# some code that gives you errno: 150
SET FOREIGN_KEY_CHECKS = 1;
Now the sql should be executed... If you really have a foreign-key problem, it would show up to you by the line where you will enable the checks again - this will fail then.. but my server is just quiet :)
usually, the mismatch between foreign key & primary key causes the
error:150.
The foreign key must have the same datatype as the primary key. Also, if the primary key is unsigned then the foreign key must also be unsigned.
I had same issue. It was related to table's column Collation and Character Set.
Make sure Character Set and Collation must be same for both columns on two tables. If you want to set a foreign key on that.
Example- If you put foreign key on userID column of userImage table referencing userID column of users table.Then Collation must be same that is utf8_general_ci and Character set utf8 for both columns of tables. Generally when you create a table mysql takes these two configuration from server settings.
After cruising through the answers above, and experimenting a bit, this is an effective way to solve Foreign Key errors in MySQL (1005 - error 150).
For the foreign key to be properly created, all MySQL asks for is:
All referenced keys MUST have either PRIMARY or UNIQUE index.
Referencing Column again MUST have identical data type to the Referenced column.
Satisfy these requirements and all will be well.
I experienced this error when have ported Windows application to Linux. In Windows, database table names are case-insensitive, and in Linux they are case-sensitive, probably because of file system difference. So, on Windows table Table1 is the same as table1, and in REFERENCES both table1 and Table1 works. On Linux, when application used table1 instead of Table1 when it created database structure I saw error #150; when I made correct character case in Table1 references, it started to work on Linux too. So, if nothing else helps, make you sure that in REFERENCES you use correct character case in table name when you on Linux.
Change the engines of your tables, only innoDB supports foreign keys
If the PK table is created in one CHARSET and then you create FK table in another CHARSET..then also you might get this error...I too got this error but after changing the charset to PK charset then it got executed without errors
create table users
(
------------
-------------
)DEFAULT CHARSET=latin1;
create table Emp
(
---------
---------
---------
FOREIGN KEY (userid) REFERENCES users(id) on update cascade on delete cascade)ENGINE=InnoDB, DEFAULT CHARSET=latin1;
This error can occur if two tables have a reference, for example, one table is Student and another table is Education, and we want the Education table to have a foreign key reference of Student table. In this instance the column data type for both tables should be same, otherwise it will generate an error.
In most of the cases the problem is because of the ENGINE dIfference .If the parent is created by InnoDB then the referenced tables supposed to be created by MyISAM & vice versa
In my case. I had problems with engine and charset because my Hosting server change settings and my new tables was MyISAM but my old tables are InnoDB. Just i changed.
Please make sure both your primary key column and referenced column have the same data types and attributes (unsigned, binary, unsigned zerofill etc).
A real edge case is where you have used an MySQL tool, (Sequel Pro in my case) to rename a database. Then created a database with the same name.
This kept foreign key constraints to the same database name, so the renamed database (e.g. my_db_renamed) had foreign key constraints in the newly created database (my_db)
Not sure if this is a bug in Sequel Pro, or if some use case requires this behaviour, but it cost me best part of a morning :/
The column of PARENT table to which you are referring to from child table has to be unique. If it is not, cause an error no 150.
I had the same error. In my case the reason for the error was that I had a ON DELETE SET NULL statement in the constraint while the field on which I put the constraint in its definition had a NOT NULL statement. Allowing NULL in the field solved the problem.
I faced this kind of issue while creating DB from the textfile.
mysql -uroot -padmin < E:\important\sampdb\createdb.sql
mysql -uroot -padmin sampdb < E:\important\sampdb\create_student.sql
mysql -uroot -padmin sampdb < E:\important\sampdb\create_absence.sql
mysql -uroot -padmin sampdb < E:\important\sampdb\insert_student.sql
mysql -uroot -padmin sampdb < E:\important\sampdb\insert_absence.sql
mysql -uroot -padmin sampdb < E:\important\sampdb\load_student.sql
mysql -uroot -padmin sampdb < E:\important\sampdb\load_absence.sql
I just wrote the above lines in Create.batand run the bat file.
My mistake is in the sequence order of execution in my sql files. I tried to create table with primary key and also foreign key. While its running it will search for the reference table but tables are not there.
So it will return those kind of error.
If you creating tables with foreign key then check the reference
tables were present or not. And also check the name of the reference
tables and fields.
I had a similar problem but mine was because i was adding a new field to an existing table that had data , and the new field was referencing another field from the parent table and also had the Defination of NOT NULL and without any DEFAULT VALUES. - I found out the reason things were not working was because
My new field needed to autofill the blank fields with a value from the parent table on each record, before the constraint could be applied. Every time the constraint is applied it needs to leave the Integrity of the table data intact. Implementing the Constraint (Foreign Key) yet there were some database records that did not have the values from the parent table would mean the data is corrupt so MySQL would NEVER ENFORCE YOUR CONSTRAINT
It is important to remember that under normal circumstances if you planned your database well ahead of time, and implemented constraints before data insertion this particular scenario would be avoided
The easier Approach to avoid this gotcha is to
Save your database tables data
Truncate the table data (and table artifacts i.e indexes etc)
Apply the Constraints
Import Your Data
I Hope this helps someone
Create the table without foreign key, then set the foreign key separately.
Perhaps this will help? The definition of the primary key column should be exactly the same as the foreign key column.
Make sure that the all tables can support foreign key - InnoDB engine
I had a similar problem when dumping a Django mysql database with a single table. I was able to fix the problem by dumping the database to a text file, moving the table in question to the end of the file using emacs and importing the modified sql dump file into the new instance.
HTH Uwe
I've corrected the problem by making the variable accept null
ALTER TABLE `ajout_norme`
CHANGE `type_norme_code` `type_norme_code` VARCHAR( 2 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL
I got the same problem when executing a series of MySQL commands. Mine occurs during creating a table when referencing a foreign key to other table which was not created yet. It's the sequence of table existence before referencing.
The solution: Create the parent tables first before creating a child table which has a foreign key.

Adding foreign key to existing table gives error 1050 table already exists

I've a table CustomizationSet with the columns:
customization_set_guid (which is a non-nullable guid and also the primary key)
creator_account_guid
and a few others
And a table with existing data Registration with the columns:
registration_id (an int and the primary key)
customization_set_guid (also a guid (so a char(36)) which is nullable, and all entries are currently null)
and a few other columns
When I try and run
ALTER TABLE Registration ADD FOREIGN KEY
(
customization_set_guid
) REFERENCES CustomizationSet (
customization_set_guid
);
in MySQL Workbench, it gives the error 1050Table '.\dbname\registration' already exists.
If I try to use the UI to add the foreign keys with the Foreign Keys tab of the Alter Table Dialog, and choose CustomizationSet as the referenced table, it doesn't let me choose customization_set_guid in the list of columns.
I'm really not sure why it won't let me add this foreign key. I've just successfully created foreign keys between tables I just added. The Registration table has existed for awhile...
I got the same error, and it was due to the fact that the foreign key already existed. What you want is just to add the constraint:
ALTER TABLE Registration
ADD CONSTRAINT idx_Registration_CustomizationSet
FOREIGN KEY (customization_set_guid)
REFERENCES CustomizationSet(customization_set_guid);
It looks like there is a bug report for this at MySQL located here:
MySQL Bug 55296
In the end, I guess they upgraded their server and it fixed the issue. From reading it, I'm not sure though. They did have some workarounds like putting in constraint names/changing them. If you think this is the same, I would request that the bug is reopened.
At one point, they mention the types didn't match and workbench was responding with the wrong error (it should have been an errno 150, or errno 121). You can see the causes for those errors here:
MySQL Foreign Key Errors and Errno 150
So a team member figured this out. The one table was set with the type utf8_general, and another was set to the type default. I didn't think this was an issue, since the default is utf8_general, but apparently mysql just looks at the type names and not the underlying type.
I got the same error, and since my case wasnt mentioned yet, i ll post this answer and hopefully it may save somebody's time!
My two tables engines, where different.
The one was InnoDB, and the other MyIsam.
To change the engine of a table:
choose table, hit alter table, and then to hit that double arrow at
the right-most of the Workbench(so it will point upwards).
Now change the engine!
Check the Storage Engine type for CustomizationSet table.
I had a same issue but i could solve it by changing engine type to
InnoDB , because few types don't support foreign key constraints.
Not sure about the table already existing, but the reason it's not letting you choose the column you want is most likely due to the columns not being the same type. Check to ensure they are both the same type, same length, and have all the same options.
I'm not sure if it's a typo but shouldn't be
ALTER TABLE Registration ADD FOREIGN KEY
(
customization_set_guid
) REFERENCES CustomizationSet (
customization_set_guid
);
be something like
ALTER TABLE Registration ADD FOREIGN KEY
customization_set_guid_fk (customization_set_guid)
REFERENCES CustomizationSet (customization_set_guid);
I had a similar problem and in the end it was a problem of Integrity Constraint.
The Foreign Key column was referencing a foreign column that didnt
exist.
Try run the following to test whether this is the case:
select r.customization_set_guid, c.customization_set_guid
from Registration r
right join CustomizationSet c
on
r.customization_set_guid = c.customization_set_guid
where isnull(c.customization_set_guid);
When using MysqlWorkbench the error is misleading. My issue was that I was trying to add a foreign key constraint on table that already had rows and one of the rows was empty (did not meet the FK constraint. Instead of complaining that constraint will fail if applied, MysqlWorkbench reported that table exists.
Removing the offending row fixed (or adding and constraint acceptable value to the field) solved the problem.

MySQL: Can't create table (errno: 150)

I am trying to import a .sql file and its failing on creating tables.
Here's the query that fails:
CREATE TABLE `data` (
`id` int(10) unsigned NOT NULL,
`name` varchar(100) NOT NULL,
`value` varchar(15) NOT NULL,
UNIQUE KEY `id` (`id`,`name`),
CONSTRAINT `data_ibfk_1` FOREIGN KEY (`id`) REFERENCES `keywords` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
I exported the .sql from the same database, I dropped all the tables and now im trying to import it, why is it failing?
MySQL: Can't create table './dbname/data.frm' (errno: 150)
From the MySQL - FOREIGN KEY Constraints Documentation:
If you re-create a table that was dropped, it must have a definition that conforms to the foreign key constraints referencing it. It must have the correct column names and types, and it must have indexes on the referenced keys, as stated earlier. If these are not satisfied, MySQL returns Error 1005 and refers to Error 150 in the error message, which means that a foreign key constraint was not correctly formed. Similarly, if an ALTER TABLE fails due to Error 150, this means that a foreign key definition would be incorrectly formed for the altered table.
Error 150 means you have a problem with your foreign key. Possibly the key on the foreign table isn't the exact same type?
You can get the actual error message by running SHOW ENGINE INNODB STATUS; and then looking for LATEST FOREIGN KEY ERROR in the output.
Source: answer from another user in a similar question
Data types must match exactly. If you are dealing with varchar types, the tables must use the same collation.
I think all these answers while correct are misleading to the question.
The actual answer is this before you start a restore, if you're restoring a dump file with foreign keys:
SET FOREIGN_KEY_CHECKS=0;
because naturally the restore will be creating some constraints before the foreign table even exists.
In some cases, you may encounter this error message if there are different engines between the relating tables. For example, a table may be using InnoDB while the other uses MyISAM. Both need to be same
Error no. 150 means a foreign key constraint failure. You are probably creating this table before the table the foreign key depends on (table keywords). Create that table first and it should work fine.
If it doesn't, remove the foreign key statement and add it after the table is created - you will get a more meaningful error message about the specific constraint failure.
There are quite a few things that can cause errno 150, so for people searching this topic, here is what I think is a close to exhaustive list (source Causes of Errno 150):
For errno 150 or errno 121, simply typing in SHOW ENGINE INNODB STATUS, there is a section called "LATEST FOREIGN KEY ERROR". Under that it will give you a very helpful error message, which typically will tell you right away what is the matter. You need SUPER privileges to run it, so if you don't have that, you'll just have to test out the following scenarios.
1) Data Types Don't Match: The types of the columns have to be the same
2) Parent Columns Not Indexed (Or Indexed in Wrong Order)
3) Column Collations Don't Match
4) Using SET NULL on a NOT NULL Column
5) Table Collations Don't Match: even if the column collations match, on some MySQL versions this can be a problem.
6) Parent Column Doesn't Actually Exist In Parent Table. Check spelling (and perhaps a space at the beginning or end of column)
7) One of the indexes on one of the columns is incomplete, or the column is too long for a complete index. Note that MySQL (unless you tweak it) has a maximum single column key length of 767 bytes (this corresponds to a varchar(255) UTF column)
In case you get an errno 121, here are a couple of causes:
1) The constraint name you chose is already taken
2) On some systems if there is a case difference in your statement and table names. This can bite you if you go from one server to another that have different case handling rules.
Sometimes MySQL is just super stupid - i can understand the reason cause of foreign-keys.. but in my case, i have just dropped the whole database, and i still get the error... why? i mean, there is no database anymore... and the sql-user i'm using has no access to any other db's on the server... i mean, the server is "empty" for the current user and i still get this error? Sorry but i guess MySQL is lying to me... but i can deal with it :) Just add these two lines of SQL around your fucky statement:
SET FOREIGN_KEY_CHECKS = 0;
# some code that gives you errno: 150
SET FOREIGN_KEY_CHECKS = 1;
Now the sql should be executed... If you really have a foreign-key problem, it would show up to you by the line where you will enable the checks again - this will fail then.. but my server is just quiet :)
usually, the mismatch between foreign key & primary key causes the
error:150.
The foreign key must have the same datatype as the primary key. Also, if the primary key is unsigned then the foreign key must also be unsigned.
I had same issue. It was related to table's column Collation and Character Set.
Make sure Character Set and Collation must be same for both columns on two tables. If you want to set a foreign key on that.
Example- If you put foreign key on userID column of userImage table referencing userID column of users table.Then Collation must be same that is utf8_general_ci and Character set utf8 for both columns of tables. Generally when you create a table mysql takes these two configuration from server settings.
After cruising through the answers above, and experimenting a bit, this is an effective way to solve Foreign Key errors in MySQL (1005 - error 150).
For the foreign key to be properly created, all MySQL asks for is:
All referenced keys MUST have either PRIMARY or UNIQUE index.
Referencing Column again MUST have identical data type to the Referenced column.
Satisfy these requirements and all will be well.
I experienced this error when have ported Windows application to Linux. In Windows, database table names are case-insensitive, and in Linux they are case-sensitive, probably because of file system difference. So, on Windows table Table1 is the same as table1, and in REFERENCES both table1 and Table1 works. On Linux, when application used table1 instead of Table1 when it created database structure I saw error #150; when I made correct character case in Table1 references, it started to work on Linux too. So, if nothing else helps, make you sure that in REFERENCES you use correct character case in table name when you on Linux.
Change the engines of your tables, only innoDB supports foreign keys
If the PK table is created in one CHARSET and then you create FK table in another CHARSET..then also you might get this error...I too got this error but after changing the charset to PK charset then it got executed without errors
create table users
(
------------
-------------
)DEFAULT CHARSET=latin1;
create table Emp
(
---------
---------
---------
FOREIGN KEY (userid) REFERENCES users(id) on update cascade on delete cascade)ENGINE=InnoDB, DEFAULT CHARSET=latin1;
This error can occur if two tables have a reference, for example, one table is Student and another table is Education, and we want the Education table to have a foreign key reference of Student table. In this instance the column data type for both tables should be same, otherwise it will generate an error.
In most of the cases the problem is because of the ENGINE dIfference .If the parent is created by InnoDB then the referenced tables supposed to be created by MyISAM & vice versa
In my case. I had problems with engine and charset because my Hosting server change settings and my new tables was MyISAM but my old tables are InnoDB. Just i changed.
Please make sure both your primary key column and referenced column have the same data types and attributes (unsigned, binary, unsigned zerofill etc).
A real edge case is where you have used an MySQL tool, (Sequel Pro in my case) to rename a database. Then created a database with the same name.
This kept foreign key constraints to the same database name, so the renamed database (e.g. my_db_renamed) had foreign key constraints in the newly created database (my_db)
Not sure if this is a bug in Sequel Pro, or if some use case requires this behaviour, but it cost me best part of a morning :/
The column of PARENT table to which you are referring to from child table has to be unique. If it is not, cause an error no 150.
I had the same error. In my case the reason for the error was that I had a ON DELETE SET NULL statement in the constraint while the field on which I put the constraint in its definition had a NOT NULL statement. Allowing NULL in the field solved the problem.
I faced this kind of issue while creating DB from the textfile.
mysql -uroot -padmin < E:\important\sampdb\createdb.sql
mysql -uroot -padmin sampdb < E:\important\sampdb\create_student.sql
mysql -uroot -padmin sampdb < E:\important\sampdb\create_absence.sql
mysql -uroot -padmin sampdb < E:\important\sampdb\insert_student.sql
mysql -uroot -padmin sampdb < E:\important\sampdb\insert_absence.sql
mysql -uroot -padmin sampdb < E:\important\sampdb\load_student.sql
mysql -uroot -padmin sampdb < E:\important\sampdb\load_absence.sql
I just wrote the above lines in Create.batand run the bat file.
My mistake is in the sequence order of execution in my sql files. I tried to create table with primary key and also foreign key. While its running it will search for the reference table but tables are not there.
So it will return those kind of error.
If you creating tables with foreign key then check the reference
tables were present or not. And also check the name of the reference
tables and fields.
I had a similar problem but mine was because i was adding a new field to an existing table that had data , and the new field was referencing another field from the parent table and also had the Defination of NOT NULL and without any DEFAULT VALUES. - I found out the reason things were not working was because
My new field needed to autofill the blank fields with a value from the parent table on each record, before the constraint could be applied. Every time the constraint is applied it needs to leave the Integrity of the table data intact. Implementing the Constraint (Foreign Key) yet there were some database records that did not have the values from the parent table would mean the data is corrupt so MySQL would NEVER ENFORCE YOUR CONSTRAINT
It is important to remember that under normal circumstances if you planned your database well ahead of time, and implemented constraints before data insertion this particular scenario would be avoided
The easier Approach to avoid this gotcha is to
Save your database tables data
Truncate the table data (and table artifacts i.e indexes etc)
Apply the Constraints
Import Your Data
I Hope this helps someone
Create the table without foreign key, then set the foreign key separately.
Perhaps this will help? The definition of the primary key column should be exactly the same as the foreign key column.
Make sure that the all tables can support foreign key - InnoDB engine
I had a similar problem when dumping a Django mysql database with a single table. I was able to fix the problem by dumping the database to a text file, moving the table in question to the end of the file using emacs and importing the modified sql dump file into the new instance.
HTH Uwe
I've corrected the problem by making the variable accept null
ALTER TABLE `ajout_norme`
CHANGE `type_norme_code` `type_norme_code` VARCHAR( 2 ) CHARACTER SET utf8 COLLATE utf8_general_ci NULL
I got the same problem when executing a series of MySQL commands. Mine occurs during creating a table when referencing a foreign key to other table which was not created yet. It's the sequence of table existence before referencing.
The solution: Create the parent tables first before creating a child table which has a foreign key.

"please select equal number of source and reference" on sqlyog

I am trying to add a foreign key constraint via sqlyog, and getting this error, although I am only select one source and one reference columns
please select equal number of source
and reference
Does anyone knows what it means in this case? Note that I do have an equal number of source and reference columns...
I came across the same issue with SQLYog v9.01. The error message is misleading and the real cause of an error can be totally different.
Things I checked to solve this are the following:
Check table engyne types, should be both InnoDb
Check if your target table is not the same as source.
Check datatypes, length and charset collation of referenced fields.
If you already have data in your tables check its consistency.
For example, you should remove all unrelated data from table B which relates to table A
DELETE target FROM B AS target LEFT JOIN A USING(id_A) WHERE A.id_A IS NULL
Finally ones in my case I had to FLUSH tables to create my constraints successfully.
Manual constraint creation from Query window can give you more information on your error type.
Just a reminder:
ALTER TABLE `B` ADD CONSTRAINT `FK_B` FOREIGN KEY (`id_A`) REFERENCES `A` (`id_A`) ON DELETE CASCADE ;
Good luck!

What does mysql error 1025 (HY000): Error on rename of './foo' (errorno: 150) mean?

I tried this in mysql:
mysql> alter table region drop column country_id;
And got this:
ERROR 1025 (HY000): Error on rename of './product/#sql-14ae_81' to
'./product/region' (errno: 150)
Any ideas? Foreign key stuff?
You usually get this error if your tables use the InnoDB engine. In that case you would have to drop the foreign key, and then do the alter table and drop the column.
But the tricky part is that you can't drop the foreign key using the column name, but instead you would have to find the name used to index it. To find that, issue the following select:
SHOW CREATE TABLE region;
This should show you the name of the index, something like this:
CONSTRAINT region_ibfk_1 FOREIGN
KEY (country_id) REFERENCES
country (id) ON DELETE NO
ACTION ON UPDATE NO ACTION
Now simply issue an:
alter table region drop foreign key
region_ibfk_1;
And finally an:
alter table region drop column
country_id;
And you are good to go!
It is indeed a foreign key error, you can find out using perror:
shell$ perror 150
MySQL error code 150: Foreign key constraint is incorrectly formed
To find out more details about what failed, you can use SHOW ENGINE INNODB STATUS and look for the LATEST FOREIGN KEY ERROR section it contains details about what is wrong.
In your case, it is most likely cause something is referencing the country_id column.
You can get also get this error trying to drop a non-existing foreign key. So when dropping foreign keys, always make sure they actually exist.
If the foreign key does exist, and you are still getting this error try the following:
SET #OLD_UNIQUE_CHECKS=##UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET #OLD_FOREIGN_KEY_CHECKS=##FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET #OLD_SQL_MODE=##SQL_MODE, SQL_MODE='TRADITIONAL';
// Drop the foreign key here!
SET SQL_MODE=#OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=#OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=#OLD_UNIQUE_CHECKS;
This always does the trick for me :)
Simply run the alter table query using 'KEY' instead of 'FOREIGN KEY' in the drop statement. I hope it will help to solve the issue, and will drop the foreign key constraint and you can change the table columns and drop the table.
ALTER TABLE slide_image_sub DROP KEY FK_slide_image_sub;
here in DROP KEY instead of DROP FOREIGN KEY,
hope it will help.
Thanks
I know, this is an old post, but it's the first hit on everyone's favorite search engine if you are looking for error 1025.
However, there is an easy "hack" for fixing this issue:
Before you execute your command(s) you first have to disable the foreign key constraints check using this command:
SET FOREIGN_KEY_CHECKS = 0;
Then you are able to execute your command(s).
After you are done, don't forget to enable the foreign key constraints check again, using this command:
SET FOREIGN_KEY_CHECKS = 1;
Good luck with your endeavor.
I had a similar issues once. I deleted the primary key from TABLE A but when I was trying to delete the foreign key column from table B I was shown the above same error.
You can't drop the foreign key using the column name and to bypass this in PHPMyAdmin or with MySQL, first remove the foreign key constraint before renaming or deleting the attribute.
Take a look in error file for your mysql database. According to Bug #26305 my sql do not give you the cause. This bug exists since MySQL 4.1 ;-)
If you are using a client like MySQL Workbench, right click the desired table from where a foreign key is to be deleted, then select the foreign key tab and delete the indexes.
Then you can run the query like this:
alter table table_name drop foreign_key_col_name;
There is probably another table with a foreign key referencing the primary key you are trying to change.
To find out which table caused the error you can run SHOW ENGINE INNODB STATUS and then look at the LATEST FOREIGN KEY ERROR section
Use SHOW CREATE TABLE categories to show the name of constraint.
Most probably it will be categories_ibfk_1
Use the name to drop the foreign key first and the column then:
ALTER TABLE categories DROP FOREIGN KEY categories_ibfk_1;
ALTER TABLE categories DROP COLUMN assets_id;
I got this error with MySQL 5.6 but it had nothing to do with Foreign keys. This was on a Windows 7 Professional machine acting as a server on a small LAN.
The client application was doing a batch operation that creates a table fills it with some external data then runs a query joining with permanent tables then dropping the "temporary" table. This batch does this approximately 300 times and this particular routine had been running week in week out for several years when suddenly we get the Error 1025 Unable to rename problem at a random point in the batch.
In my case the application was using 4 DDL statements a CREATE TABLE followed by 3 CREATE INDEX, there is no foreign key. However only 2 of the indexes actually get created and the actual table .frm file was renamed, at the point of failure.
My solution was to get rid of the separate CREATE INDEX statements and create them using the CREATE TABLE statement. This at the time of writing has solved the issue for me and my help someone else scratching their head when they find this thread.
I'd guess foreign key constraint problem. Is country_id used as a foreign key in another table?
I'm not DB guru but I think I solved a problem like this (where there was a fk constraint) by removing the fk, doing my alter table stuff and then redoing the fk stuff.
I'll be interested to hear what the outcome is - sometime mysql is pretty cryptic.
In my case, I was using MySQL workbench and I faced the same issue while dropping one of my columns in a table. I could not find the name of the foreign key. I followed the following steps to resolve the issue:
Rt. click on your schema and select 'schema inspector'. This gives you various tables, columns, indexes, ect.
Go to the tab named 'Indexes' and search the name of the column under the column named 'Column'. Once found check the name of the table for this record under the column name 'Table'. If it matches the name of the table you want, then note down the name of the foreign key from the column named 'Name'.
Now execute the query : ALTER table tableNamexx DROP KEY foreignKeyName;
Now you can execute the drop statement which shall execute successfully.
Doing
SET FOREIGN_KEY_CHECKS=0;
before the Operation can also do the trick.
averageRatings= FOREACH groupedRatings GENERATE group AS movieID, AVG(ratings.rating) AS avgRating, COUNT(ratings.rating) AS numRatings;
If you are using any command like above you must use group in small letters. This may solve your problem it solved mine. At least in PIG script.