420

I want to add a Foreign Key to a table called "katalog".

ALTER TABLE katalog 
ADD CONSTRAINT `fk_katalog_sprache` 
FOREIGN KEY (`Sprache`)
REFERENCES `Sprache` (`ID`)
ON DELETE SET NULL
ON UPDATE SET NULL;

When I try to do this, I get this error message:

Error Code: 1005. Can't create table 'mytable.#sql-7fb1_7d3a' (errno: 150)

Error in INNODB Status:

120405 14:02:57 Error in foreign key constraint of table mytable.#sql-7fb1_7d3a:

FOREIGN KEY (`Sprache`)
REFERENCES `Sprache` (`ID`)
ON DELETE SET NULL
ON UPDATE SET NULL:
Cannot resolve table name close to:
(`ID`)
ON DELETE SET NULL
ON UPDATE SET NULL

When i use this query it works, but with wrong "on delete" action:

ALTER TABLE `katalog` 
ADD FOREIGN KEY (`Sprache` ) REFERENCES `sprache` (`ID` )

Both tables are InnoDB and both fields are "INT(11) not null". I'm using MySQL 5.1.61. Trying to fire this ALTER Query with MySQL Workbench (newest) on a MacBook Pro.

Table Create Statements:

CREATE TABLE `katalog` (
`ID` int(11) unsigned NOT NULL AUTO_INCREMENT,
`Name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
`AnzahlSeiten` int(4) unsigned NOT NULL,
`Sprache` int(11) NOT NULL,
PRIMARY KEY (`ID`),
UNIQUE KEY `katalogname_uq` (`Name`)
 ) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=DYNAMIC$$

CREATE TABLE `sprache` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
 `Bezeichnung` varchar(45) NOT NULL,
 PRIMARY KEY (`ID`),
 UNIQUE KEY `Bezeichnung_UNIQUE` (`Bezeichnung`),
KEY `ix_sprache_id` (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8
Sankar
  • 6,908
  • 2
  • 30
  • 53
frgtv10
  • 5,300
  • 4
  • 30
  • 46
  • 1
    Since you didn't post the output of `SHOW CREATE TABLE`, I can only but ask - is the column name really ID, uppercased? – N.B. Apr 05 '12 at 12:09
  • Well, it's easier to spot now - `katalog` has `int(11) unsigned`. `sprache` doesn't have the `usigned` part, therefore two columns aren't the same. – N.B. Apr 05 '12 at 12:15
  • Do you mean, the both Primary fields must be same data type? – frgtv10 Apr 05 '12 at 12:19
  • 4
    This is the problem with your design: first, you're referencing two `auto_increment` columns which is bad. Also, the MySQL manual says: `Corresponding columns in the foreign key and the referenced key must have similar internal data types inside InnoDB so that they can be compared without a type conversion. The size and sign of integer types must be the same. The length of string types need not be the same. For nonbinary (character) string columns, the character set and collation must be the same.`. Therefore, yes, **similar** data type and the same sign. – N.B. Apr 05 '12 at 12:21
  • 2
    I'm not referencing two auto_increment fields. katalog.Sprache (not auto) -> sprache.ID (auto) – frgtv10 Apr 05 '12 at 12:23
  • A +1 to N.B. In my case, I had a script where the first letter in the table name wasn't upper-cased in the constraint definition. – Aaron Newton Mar 31 '13 at 12:39

16 Answers16

704

To add a foreign key (grade_id) to an existing table (users), follow the following steps:

ALTER TABLE users ADD grade_id SMALLINT UNSIGNED NOT NULL DEFAULT 0;
ALTER TABLE users ADD CONSTRAINT fk_grade_id FOREIGN KEY (grade_id) REFERENCES grades(id);
Steen Schütt
  • 1,355
  • 1
  • 17
  • 31
iltaf khalid
  • 9,928
  • 5
  • 30
  • 34
  • 14
    Reasons help me understand and remember. This is because you can't add a foreign key to an non-unsigned field, correct? – Z2VvZ3Vp Sep 28 '15 at 21:25
  • 12
    @PixMach, the answer is no. You can have signed integers as foreign keys. As N.B. noted on the question, the type and sign of the fields need to match. So if your primary key in the lookup table is UNSIGNED, then the foreign key field must also be UNSIGNED. If the primary key field is SIGNED, then foreign key field must also be signed. Think of it this way: whatever the column in the one table is defined as in a SHOW CREATE TABLE, it needs to have the same definition in the other table. – Ben Keene Sep 19 '16 at 20:38
  • 1
    Note that this could also be done with a single query (might be better in case of failure etc) – Stijn de Witt Dec 03 '16 at 15:19
  • And do not forget to derive your index column on your refrence table, if you re using phpmyadmin mysql as MariaDb as database storege i guess it work for oracle mysql as well – Michael Feb 24 '17 at 18:06
  • 7
    I had to run "SET FOREIGN_KEY_CHECKS=0;" before running the ADD CONSTRAINT command or SQL would complain "Cannot add or update a child row: a foreign key constraint fails". – Erin Geyer Mar 08 '17 at 13:03
  • 6
    Do _not_ just run "SET FOREIGN_KEY_CHECKS=0;" if you get the error "a foreign key constraint fails", you obviously have bad data that you must fix or else you will get bigger problems down the line. – MazeChaZer Jun 11 '18 at 12:05
  • 1
    @Erin Geyer, its been 2 years or so, but the 'Cannot add or update a child row: a foreign key constraint fails' usually happens because of data inconsistency between a newly added column which you have set as a foreign key reference to a column on another table which does not yet have the data on the column it refers to. For example, the newly added column usually contains empty or default data while the column it refers to already has data. In this scenario: Create the new column, import the data from the existing column it is to refer to, then set the new column as a foreign key reference. – gbenroscience Jan 30 '19 at 08:38
  • 1
    @StijndeWitt But you will lose the liberty of having a named constraint which sucks when you have to delete it because they will be autogenerated – TheRealChx101 Oct 13 '22 at 12:08
  • 1
    For any error, read this https://stackoverflow.com/q/8434518/6576302 – C.F.G Feb 21 '23 at 18:27
95

Simply use this query, I have tried it as per my scenario and it works well

ALTER TABLE katalog ADD FOREIGN KEY (`Sprache`) REFERENCES Sprache(`ID`);
SagarPPanchal
  • 9,839
  • 6
  • 34
  • 62
  • 3
    You need to put a warning/disclaimer that this will create a constraint name for you. Something which will have grave consequences when dealing with database migrations when you want to modify your constraints. It's always good practice to name things. – TheRealChx101 Dec 04 '22 at 23:58
  • For any error, read this https://stackoverflow.com/q/8434518/6576302 – C.F.G Feb 21 '23 at 18:27
44

Simple Steps...

ALTER TABLE t_name1 ADD FOREIGN KEY (column_name) REFERENCES t_name2(column_name)
J. Chomel
  • 8,193
  • 15
  • 41
  • 69
Amjath Khan
  • 541
  • 4
  • 5
18
FOREIGN KEY (`Sprache`)
REFERENCES `Sprache` (`ID`)
ON DELETE SET NULL
ON UPDATE SET NULL;

But your table has:

CREATE TABLE `katalog` (
`Sprache` int(11) NOT NULL,

It cant set the column Sprache to NULL because it is defined as NOT NULL.

Bill
  • 181
  • 1
  • 2
16

check this link. It has helped me with errno 150: http://verysimple.com/2006/10/22/mysql-error-number-1005-cant-create-table-mydbsql-328_45frm-errno-150/

On the top of my head two things come to mind.

  • Is your foreign key index a unique name in the whole database (#3 in the list)?
  • Are you trying to set the table PK to NULL on update (#5 in the list)?

I'm guessing the problem is with the set NULL on update (if my brains aren't on backwards today as they so often are...).

Edit: I missed the comments on your original post. Unsigned/not unsigned int columns maybe resolved your case. Hope my link helps someone in the future thought.

ZZ-bb
  • 2,157
  • 1
  • 24
  • 33
10

How to fix Error Code: 1005. Can't create table 'mytable.#sql-7fb1_7d3a' (errno: 150) in mysql.

  1. alter your table and add an index to it..

    ALTER TABLE users ADD INDEX index_name (index_column)
    
  2. Now add the constraint

    ALTER TABLE foreign_key_table
    ADD CONSTRAINT foreign_key_name FOREIGN KEY (foreign_key_column)
    REFERENCES primary_key_table (primary_key_column) ON DELETE NO ACTION
    ON UPDATE CASCADE;
    

Note if you don't add an index it wont work.

After battling with it for about 6 hours I came up with the solution I hope this save a soul.

Siong Thye Goh
  • 3,518
  • 10
  • 23
  • 31
Kwed
  • 257
  • 3
  • 4
8

MySQL will execute this query:

ALTER TABLE `db`.`table1`
ADD COLUMN `col_table2_fk` INT UNSIGNED NULL,
ADD INDEX `col_table2_fk_idx` (`col_table2_fk` ASC),
ADD CONSTRAINT `col_table2_fk1`
FOREIGN KEY (`col_table2_fk`)
REFERENCES `db`.`table2` (`table2_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;

Cheers!

akelec
  • 3,797
  • 3
  • 41
  • 39
4

When you add a foreign key constraint to a table using ALTER TABLE, remember to create the required indexes first.

  1. Create index
  2. Alter table
Maksym Polshcha
  • 18,030
  • 8
  • 52
  • 77
  • I created index for both. When I try to run i get the same error message as before. When I disclaim the "on delete on update" part it works but with the wrong "on delete" action ;) – frgtv10 Apr 05 '12 at 12:32
  • @frgtv10 the most likely the tables data conflicts with "on delete". – Maksym Polshcha Apr 05 '12 at 12:43
4

try all in one query

  ALTER TABLE users ADD grade_id SMALLINT UNSIGNED NOT NULL DEFAULT 0,
      ADD CONSTRAINT fk_grade_id FOREIGN KEY (grade_id) REFERENCES grades(id);
manoj
  • 3,391
  • 2
  • 20
  • 30
4

step 1: run this script

SET FOREIGN_KEY_CHECKS=0;

step 2: add column

ALTER TABLE mileage_unit ADD COLUMN COMPANY_ID BIGINT(20) NOT NULL

step 3: add foreign key to the added column

ALTER TABLE mileage_unit
ADD FOREIGN KEY (COMPANY_ID) REFERENCES company_mst(COMPANY_ID);

step 4: run this script

SET FOREIGN_KEY_CHECKS=1;
sɐunıɔןɐqɐp
  • 3,332
  • 15
  • 36
  • 40
3
ALTER TABLE child_table_name ADD FOREIGN KEY (child_table_column) REFERENCES parent_table_name(parent_table_column);

child_table_name is that table in which we want to add constraint. child_table_column is that table column in which we want to add foreign key. parent table is that table from which we want to take reference. parent_table_column is column name of the parent table from which we take reference

1

this is basically happens because your tables are in two different charsets. as a example one table created in charset=utf-8 and other tables is created in CHARSET=latin1 so you want be able add foriegn key to these tables. use same charset in both tables then you will be able to add foriegn keys. error 1005 foriegn key constraint incorrectly formed can resolve from this

1

The foreign key constraint must be the same data type as the primary key in the reference table and column

Golden Lion
  • 3,840
  • 2
  • 26
  • 35
0
 ALTER TABLE TABLENAME ADD FOREIGN KEY (Column Name) REFERENCES TableName(column name)

Example:-

ALTER TABLE Department ADD FOREIGN KEY (EmployeeId) REFERENCES Employee(EmployeeId)
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
0

i geted through the same problem. I my case the table already have data and there were key in this table that was not present in the reference table. So i had to delete this rows that disrespect the constraints and everything worked.

0

Double check if the engine and charset of the both tables are the same.

If not, it will show this error.

ikhvjs
  • 5,316
  • 2
  • 13
  • 36