Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find which rows where foreign key constraint fail

While trying to add a foreign Key constraint to two very large tables, I get the error.

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails

This is usually due to some data in the primary table not present in the foreign table, normally I check for known anomalies like null values, out of range values etc, once these are taken care of, I can get the constraint satisfied. However this time the problem is more subtle.

What I want to know is there any way to query for all the rows which are causing the constraint to fail??

like image 239
Manquer Avatar asked Dec 05 '13 04:12

Manquer


People also ask

How do I fix foreign key constraint failure?

The error message itself showing there is a foreign key constraint error, which means you are deleting a parent table where the child table contains the Primary table identifier as a foreign key. To avoid this error, you need to delete child table records first and after that the parent table record.

How do I find foreign key constraints in SQL?

Using SQL Server Management Studio Open the Table Designer for the table containing the foreign key you want to view, right-click in the Table Designer, and choose Relationships from the shortcut menu. In the Foreign Key Relationships dialog box, select the relationship with properties you want to view.

What is a foreign key constraint fails?

Cannot add or update a child row: a foreign key constraint fails essentially means that, you are trying to add a row to your Ordrelinje table for which no matching row (OrderID) is present in Ordre table. You must first insert the row to your Ordre table.

What happens to a foreign key when a table is dropped?

When you drop a foreign key using the DROP FOREIGN KEY clause of the ALTER TABLE statement, Db2 drops the corresponding referential relationships. (You must have the ALTER privilege on the dependent table and either the ALTER or REFERENCES privilege on the parent table.)


1 Answers

Assuming you have following table, and FK relationship.

parent(parent_id (PK), name)
child(child_id, name, parent_id (FK));

You could find which rows are missing in parent table but exists in child table, using following LEFT JOIN:

SELECT child.parent_id
FROM child LEFT JOIN parent ON child.parent_id = parent.parent_id
WHERE parent.parent_id IS NULL;
like image 74
Jason Heo Avatar answered Oct 04 '22 19:10

Jason Heo