I have a query which updates single column of multiple records using column value from another table. For example below are the tables--
Table A
+-----------------+---------------------+------+
| id(primary_key) | user_id(unique_key) | f_id |
+-----------------+---------------------+------+
| 1 | 1 | 11 |
+-----------------+---------------------+------+
| 2 | 3 | 22 |
+-----------------+---------------------+------+
Table B
+----+------+
| id | f_id |
+----+------+
| 1 | 11 |
+----+------+
| 3 | 22 |
+----+------+
Now I tried to update user_id
column for all records in Table A
using id
column from Table B
on basis of f_id
column which is common using below query.
UPDATE
A
SET
user_id = B.id
FROM
B
WHERE A.f_id = B.f_id
user_id
column in Table A
is unique which generates an error on bulk update as:
ERROR: duplicate key value violates unique constraint "A_user_id_key" DETAIL: Key (user_id)=(221207) already exists.
But when I update this particular record using below query
UPDATE
A
SET
user_id = 221207
FROM
B
WHERE A.f_id = B.f_id
it executes successfully without any error. Only bulk updates shows that error. I don't get what is going wrong.
user_id
column