Skip to content
Advertisement

How to combine two records while keeping all referencing records?

PostgreSQL 11.1

I have struggled with this problem for a long time. (I have tried to improve the question from before).

Problem: A person has two different names in table tempA. Each name has its associated records in table tempB. How can I move all the records associated with one name to the other name, then delete the name?

Example: I have two names –“Tom” and “Bob”. I want to change all the records associated with “Bob” to “Tom”, then remove “Bob” from the database.

How is this done while keeping the associated records in table tempb?

The goal I am trying to reach is:

This is what I’ve tried, but it continues to fail:

ERROR: update or delete on table “tempa” violates foreign key constraint “foo_bar_fk” on table “tempb” DETAIL: Key (id)=(2) is still referenced from table “tempb”.

It seems I cannot get the UPDATE to occur before the Delete is enforced.

Any help is most appreciated. TIA

Advertisement

Answer

You would need to update the child table first, then delete from the parent – the foreign key constraints prevents you from proceeding the other way around.

Consider:

Demo on DB Fiddle

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