postgres db에 insert 하는 과정에서 다음 오류가 발생하였다.
ERROR: ON CONFLICT DO UPDATE command cannot affect row a second time
Hint: Ensure that no rows proposed for insertion within the same command have duplicate constrained values.
찾아보니, `ON CONFLICT DO UPDATE` 구문을 사용할 때, 동일한 트랜잭션 내에서 중복된 키 값이 여러 번 발생하는 경우에 발생하는 오류이다. 구체적으로, 한 트랜잭션에서 같은 키를 가진 여러 행을 동시에 삽입하려고 하여 발생하는 것이다.
예를 들어 아래와 같은 쿼리를 실행할 때,
INSERT INTO score
(name, math, english)
values
('paul', 100, 70),
('paul', 100, 50)
ON CONFLICT ON CONSTRAINT score_name_key
DO UPDATE
SET (math, english) = (excluded.math, excluded.english)
where school.english < excluded.english;
score의 name을 key값으로 지정했는데, 동일한 paul이 한 트랜잭션 내에서 삽입되려고하여 업데이트되어 바뀌는 방식이 아니라 오류가 나는 것이다.
즉 개별 트랜잭션으로 처리하거나, 미리 키값을 확인한다음 진행해줘야 한다.
Reference
Upsert error (On Conflict Do Update) pointing to duplicate constrained values
I have a problem with ON CONFLICT DO UPDATE in Postgres 9.5 when I try to use more than one source in the FROM statement. Example of working code: INSERT INTO new.bookmonographs (citavi_id,
stackoverflow.com
[PostgreSQL] upsert(insert .. conflict on ..) 구문 사용하기
참고 URL : http://www.postgresqltutorial.com/postgresql-upsert/ 'ON CONFLICT' 구문은 PostgreSQL 9.5부터 지원한다. tutorial이 잘 설명되어 있어서 특별히 추가할 내용은 없지만, 내가 삽질했던 실수가 있어서 누군가
sungtae-kim.tistory.com
'알쓸신잡' 카테고리의 다른 글
[pgAdmin error] Your account is locked. Please contact the Administrator. (0) | 2024.10.18 |
---|---|
Unable to install extension 'ms-toolsai.jupyter' as it is not compatible with VS Code (0) | 2024.09.27 |
Crontab+anaconda (0) | 2024.08.13 |
Gitlab to Github by mirroring (0) | 2024.08.10 |
CUDA call failed lazily at initialization with error: device >= 0 && device < num_gpus INTERNAL ASSERT FAILED at (0) | 2024.08.05 |