Home > Blockchain >  Postgresql - update rows or delete on unique constraint violation
Postgresql - update rows or delete on unique constraint violation

Time:10-02

I have a many-to-many table 'permit_role' as below:

permit_id role_id
permit_1 role_1
permit_2 role_1
permit_3 role_3
permit_4 role_1
permit_4 role_2

It has a unique constraint (permit_id, role_id).

I need to update permits as below:

permit_1 --> permit_5

permit_2 --> permit_5

So it`s impossible to do just

UPDATE permit_role SET permit_id = 'permit_5' WHERE permit_id = 'permit_1';

UPDATE permit_role SET permit_id = 'permit_5' WHERE permit_id = 'permit_2';

because I`ll got a unique constraint violation (two rows with (permit_5, role_1)). In this case I need the duplicated rows just to be deleted so I have only one such row in the end.

I thought about temp tables but it seems to difficult, please advise what is the easiest way to achieve my goal.

CodePudding user response:

Try a CTE:

WITH old_rows AS (
   DELETE FROM permit_role
   WHERE permit_id = 'permit_1'
   RETURNING role_id
)
INSERT INTO permit_role (permit_id, role_id)
SELECT 'permit_5', role_id
FROM old_rows
ON CONFLICT (permit_id, role_id) DO NOTHING;

Then repeat for permit_2. The ON CONFLICT clause will keep you from inserting duplicates without getting an error.

  • Related