226

table #1:

Field Type Null Key Default Extra
UserID int(11) NO PRI NULL auto_increment
Password varchar(20) NO
Username varchar(25) NO
Email varchar(60) NO

table #2:

Field Type Null Key Default Extra
UserID int(11) NO MUL
PostID int(11) NO PRI NULL auto_increment
Title varchar(50) NO
Summary varchar(500) NO

Error:

com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (myapp/table2, CONSTRAINT table2_ibfk_1 FOREIGN KEY (UserID) REFERENCES table1 (UserID))

What have I done wrong? I read http://www.w3schools.com/Sql/sql_foreignkey.asp and I don't see what's wrong.

francisco
  • 1,387
  • 2
  • 12
  • 23
Tom
  • 2,289
  • 2
  • 17
  • 8
  • 6
    Can you post the query that trigger the error? – Damp Feb 15 '11 at 15:13
  • 54
    In an nutshell, you are trying to insert/update a value in `table2.UserID` that does not exist in `table1.UserID`. – Joe Stefanelli Feb 15 '11 at 15:18
  • Not sure why but after moving my database from a windows environment to Linux, I had to delete and recreate a relation (that's when I noticed the issue). The value did exist, but removing and re-adding the relation fixed it. You may need to be pretty careful doing so obviously. – johnsnails Jul 07 '15 at 06:07

26 Answers26

297

You're getting this error because you're trying to add/update a row to table2 that does not have a valid value for the UserID field based on the values currently stored in table1. If you post some more code I can help you diagnose the specific cause.

Brian Driscoll
  • 19,373
  • 3
  • 46
  • 65
  • 1
    PreparedStatement st = connection.prepareStatement("Insert into table2 (UserID, PostID, Title, Summary)" + "values (UserID, ?, ?, ?)"); – Tom Feb 15 '11 at 15:19
  • 22
    not sure what the downvote is for; my answer is perfectly valid and correct. – Brian Driscoll Feb 15 '11 at 15:20
  • Hmm... it's definitely not a good idea to mix named parameters with unnamed parameters in your prepared statement. it should be "values (?, ?, ?, ?)" with the appropriate value for UserID specified in your execute statement. – Brian Driscoll Feb 15 '11 at 15:24
  • So I need to do to another SQL statement to get the userid from table1? – Tom Feb 15 '11 at 15:25
  • Yes - the value you specify for UserID must be a value that currently exists in table1. – Brian Driscoll Feb 15 '11 at 15:25
  • If I create a select statement to get the userid, do i store that in a variable? If so, how? Basically how do i pass the userid from the select statement to the insert statement? – Tom Feb 15 '11 at 15:36
  • Yes, you'd store the value of UserID from your select statement in a variable. I'm not sure what the Java syntax would be for getting the value from the select query into a variable, unfortunately. nonetheless, you'd store that value in a var and then put that var into the execute statement for your insert. – Brian Driscoll Feb 15 '11 at 15:59
  • 6
    Most likely a 0 , replace it by Null if it's the case – Jeffrey Nicholson Carré Mar 15 '13 at 21:03
137

It means that you're trying to insert into table2 a UserID value that doesn't exist in table1.

ᴍᴇʜᴏᴠ
  • 4,804
  • 4
  • 44
  • 57
Rami C
  • 1,903
  • 1
  • 12
  • 14
  • 1
    I had this experience when I was adding a foreign key with ID 0, which cannot reference to the key in other table as the table does not have the record with ID 0 – samheihey Mar 26 '21 at 08:17
  • im having this same issue, im trying to add a new entity that has id 0 – Vinicius Bassi Sep 14 '22 at 00:01
125

A simple hack can be to disable foreign key checks before performing any operation on the table. Simply query

SET FOREIGN_KEY_CHECKS=0

This will disable foreign key matching against any other tables. After you are done with the table enable it again

SET FOREIGN_KEY_CHECKS=1

This works for me a lot of times.


Please note that you enter the DANGER ZONE when you do this. While there are certainly valid use cases, you should only do this when you are certain you understand the implications.

Dennis Haarbrink
  • 3,738
  • 1
  • 27
  • 54
Sandeep Giri
  • 1,318
  • 1
  • 9
  • 4
58

I discovered another weird case: If you accidentally create a foreign key from an InnoDB table to a MyISAM table, MySQL throws this error at time of insert even if the data is otherwise valid.

See http://nick.zoic.org/art/mysql-foreign-key-error/

Babar Al-Amin
  • 3,939
  • 1
  • 16
  • 20
NickZoic
  • 7,575
  • 3
  • 25
  • 18
  • 2
    Yes, I have the same problem. Two tables should be InnoDB! – emeraldhieu Dec 25 '15 at 04:03
  • 3
    I had the same problem, thanks for the tip. Here's a link to MySQL documentation on how to convert tables from MyISAM to InnoDB https://dev.mysql.com/doc/refman/5.7/en/converting-tables-to-innodb.html TLDR: ALTER TABLE table_name ENGINE=InnoDB; – Guilherme Vaz Sep 25 '17 at 20:41
  • 1
    Indeed, this was the case in my database. I decided to change MyISAM engine to InnoDB. Finally, I can work with the database the way I wanted to. – Mike Dec 11 '19 at 12:44
  • 1
    I spent hours looking for an answer, finally thank you! – Gilad Dahan Aug 19 '21 at 14:12
19

You're getting this error because there are some value int table2.UserID that is not exists on table1.UserID (I guess that you have setted table2.UserID value manualy before you created this foreign key).
One example for this scene: table1.UserID get values 1,2,3 and table2.UserID get values 4 (add by manual). So when you make a foreign key, they can't find UserID = 4 from table1 and the error will ocurse.
To fix this error, just remove UserID = 4 from table2 or you can empty both of them and then create the foreign key and.
Good luck!

Justin
  • 4,400
  • 2
  • 32
  • 36
16

This took me a while to figure out. Simply put, the table that references the other table already has data in it and one or more of its values does not exist in the parent table.

e.g. Table2 has the following data:

UserID    PostID    Title    Summary
5         1         Lorem    Ipsum dolor sit

Table1

UserID    Password    Username    Email
9         ********    JohnDoe     john@example.com

If you try to ALTER table2 and add a foreign key then the query will fail because UserID=5 doesn't exist in Table1.

Sbudah
  • 163
  • 1
  • 4
10

If you have inserted a row into table 1 before creating the foreign key in table 2, then you will get a foreign key constraint error, because the auto increment value is 2 in table 1 and 1 in table 2. To solve this you have to truncate table 1 and set the auto increment value back to 1. Then you can add table 2.

Nicolai Lissau
  • 7,298
  • 5
  • 43
  • 57
10

Make sure you have set database engine to InnoDB because in MyISAM foreign key and transaction are not supported

Aman Maurya
  • 1,305
  • 12
  • 26
10

Just a little bit fix: Make the JoinColumn 'nullable = true' in Table1 and 'UserID' field 'insertable=false' and 'nullable=true' in Table2.

In Table1 Entity:

@OneToMany(targetEntity=Table2.class, cascade = CascadeType.ALL)
@JoinColumn(name = "UserID", referencedColumnName = "UserID", nullable = true)
private List<Table2> table2List;

In Table2 Entity:

@Column(insertable = false, nullable = true)
private int UserID;
  • This answer totally solved my problem, thank you so much for sharing this. The key for me was adding the @Column(insertable=false, nullable=true) on the filed that i am using as the foraeing key in my child object/table. – Israelm Feb 12 '19 at 00:16
6

I just had the same problem the solution is easy.

You are trying to add an id in the child table that does not exist in the parent table.

check well, because InnoDB has the bug that sometimes increases the auto_increment column without adding values, for example, INSERT ... ON DUPLICATE KEY

Blaztix
  • 1,223
  • 1
  • 19
  • 28
5

I had a similar issue. You are trying to apply foreign key on a table which has content and the column is not nullable. You have two options.

  1. Make the column you want to apply foreign key constraints on to be nullable. That way the foreign key will apply knowing that some fields can be nullable. (This is what i did.)
  2. Create the column you want to apply foreign key constraint on, write a query to insert the foreign key into the column and then apply the foreign key constraints. (Did not try this but it should work)
Jacob
  • 407
  • 5
  • 8
4

Make sure the value that you are inserting into the foreign key exists in the parent table. That helped me. For example if you insert user_id = 2 into table.2, but table.1 does not have a user_id = 2, then the constraint will throw an error. Mine was error code #1452 to be exact. Hope this helps anyone else with the same problem!

clemens
  • 16,716
  • 11
  • 50
  • 65
Dustin Hammack
  • 154
  • 1
  • 1
  • 15
2

I had the same issue, and the reason was that I had a row in the first table before adding the foreign key.

Ouissal
  • 1,519
  • 2
  • 18
  • 36
2

Delete indexes of the UserID field of table2. Its suits for me

Anton
  • 21
  • 1
1

I also got this error: "Cannot add or update a child row: a foreign key constraint fails". I got the error when adding a new row to the parent table

The problem was that the foreign key constraint had been defined on the parent table instead of the child table.

Nadir Latif
  • 3,690
  • 1
  • 15
  • 24
1

I also faced same issue and the issue was my parent table entries value not match with foreign key table value. So please try after clear all rows..

Justine Jose
  • 130
  • 2
  • 7
1

In case if the solutions provided by others didn't work. Then you should try checking the Database Engines of the Parent and Child Tables.In my case, I had the parent tables' engine set to "MyISAM", changing it to InnoDB fixed it.

Hope this helps others who are stuck like me.

1

You should not put an ondelete field against a cascade in the database.

So set the onDelete field to RESTRICT

Good luck ♥

0

Yet another weird case that gave me this error. I had erroneously referenced my foreign keys to the id primary key. This was caused by incorrect alter table commands. I found this out by querying the INFORMATION_SCHEMA table (See this stackoverflow answer)

The table was so confused it could not be fixed by any ALTER TABLE commands. I finally dropped the table and reconstructed it. This got rid of the integrityError.

Community
  • 1
  • 1
Vicky T
  • 1,643
  • 4
  • 15
  • 12
0

Maybe whilst you added the userID column, there is a data for that certain table that it is established so it will have a default value of 0, try adding the column without the NOT NULL

WTFZane
  • 592
  • 1
  • 4
  • 25
0

İf you use mysql index or relation between tables, firstly you delete the colums(for example:city_id) and create new colums with same name(for example:city_id).Then try again...

Mahmut Aydın
  • 831
  • 13
  • 21
0

Is there any existing data that the table contains? If so, try to clear out all the data in the table you want to add a foreign key. Then run the code (add a foreign key) again.

I encountered this problem so many times. This clearing out the all data in the table works when you want to add foreign key on a existing table.

Hope this works :)

Noldy
  • 11
0

That error occurs when you want to add a foreign key with values that don't exist in the primary key of the parent table. You must be sure that the new foreign key UserID in table2 has values that exist in the table1 primary key, sometimes by default it is null or equal to 0.

You could first update all the fields of the foreign key in table2 with a value that exists in the primary key of table1.

update table2 set UserID = 1 where UserID is null

If you want to add different UserIDs you must modify each row with the values you want.

Vladimir Salguero
  • 5,609
  • 3
  • 42
  • 47
0

If you added the column with checked box NOT NULL You will have surprise to see all rows have value = 0 for that column, When you try to add foreign key maybe you don't have a row in foreign table2, with value 0 so mysql error popup show

BoBiTza
  • 98
  • 13
0

Thanks @BrianDriscoll,

Personally the problem originated from the Form select field.

This is how i had done it

<select name="gender" class="form-select" required>
<option selected>Select Gender </option>
<?php foreach($gender as $g):?>
<option value="<?= $g->id"><?= $g->name;?>
</option>
<?php endif;?>
</select>

So this line "<option selected>Select Gender </option>" kept giving that error everytime I had not selected that field.

Therefore changed it to "<option value="">Select Gender </option>".

Infact when I rectified it, even the required started working.

lwegaba
  • 121
  • 1
  • 6
-1

child table foreign key constraint is failing

This issue may rise due to following reason:

If you are doing it in Spring mvc, you need to explicitly describe the id type, because sometimes mysql fails to recognize the type of id. so you explicitly set as in both tables in your entity class@GeneratedValue (strategy = GenerationType.IDENTITY)

ndmeiri
  • 4,979
  • 12
  • 37
  • 45