JitendraBhatt.com | Blog | My Albums | Web Samples Thursday February 09, 2012 
Aug 09

ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails

Here’s what happened and how I fixed the error:

I had two tables I was working on – CUST and MEDIA tables. I was looking to modify the cust table and make the MEDIA_ID (PK for MEDIA TABLE) a FOREIGN KEY in the CUST TABLE. However, after several attempts I kept getting the aforementioned error.

Here is my ALTER statement: ALTER TABLE CUST ADD FOREIGN KEY (MEDIA_ID) REFERENCES MEDIA (MEDIA_ID);

CUST table

MEDIA table

I researched this ERROR online and found many possible fixes however, none of them applied/worked for my problem. Therefore, I decided to start over and do a thorough inspection on both of these two tables…

In a matter of seconds I found the problem….If you will take a look at the two images above you will notice that the MEDIA_ID in the CUST table was defined as a decimal(1,0) while the MEDIA table defined MEDIA_ID as a decimal(10,0). Therefore, my REFERENCE clause was failing since the MEDIA_ID in the MEDIA table accepts different values opposed to the MEDIA_ID in the CUST table.

Leave a Reply