Skip to content
Advertisement

Update or Delete Violates foreign key constraint

I have two tables that look like the following.

In this example the book_id column is the primary key in the book table, and the referenced foreign key in the booksubcategory table. When I try and run the following sql, I receive the error:

Here is what the SQL looks like.

In this situation the sql should update the columns because the book_special_key already exists in the book table.

I’m familiar with the reason why updates and deletes on foreign key constraints can fail for integrity reasons, but in my case I’m not updating the book_id directly, just the columns in the book table. Also I have ON DELETE CASCADE set on the foreign key in the child table. Can someone tell my why I’m experiencing this issue?

Advertisement

Answer

The inserted row clashes on unique key special_book_id, then the conflict rule tries to update the duplicate row.

But what is the value book_id of a NEW row that was not yet inserted due to conflicts and is autogen? Well, either null or a new serial.

So, whatever the case, you are updating book_id to null or a new serial and it fails as the old book_id value, that is disappearing, has references.

Remove the update to column book_id and it should work.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement