본문 바로가기

Database/DB

postgresql SQL Error [42P10]: ERROR: there is no unique or exclusion constraint matching the ON CONFLICT specification

 

문제점

 

다음과 같이 insert on conflict 구문일때 실행시 에러가 발생했다.

INSERT INTO frame (id, chnl_id, frame_body_cntt, create_at, updated_at) 
    VALUES ('A0016','A','오렌지', now(), now())
    ON CONFLICT (id)
        DO nothing;

 

 

해결책

공식문서를 보자!!

https://www.postgresql.org/docs/current/sql-insert.html

 

INSERT

INSERT INSERT — create new rows in a table Synopsis [ WITH [ RECURSIVE ] with_query [, ...] ] INSERT …

www.postgresql.org

 

on conflict 절을 보면 다음과 같이 정의되어 있다.

지정된 conflict_target의 칼럼은 하나 이상의 index_column_name열 또는 index_expression표현식을 순서에 관계없이  모든 고유 인덱스를 on confilict의 조건으로 유추(선택)됩니다. 

ON CONFLICT로 upserting할 때는 index_predicate를 지정해야 합니다.

 

말이 어렵게 써있지만, 결국 해당 테이블에서 해당 row임을 나타내는 고유한 유니크값을 on conflict (요기에) 넣어줘야 한다.

나의 경우 해당 테이블은 id 뿐만아니라 chnl_id 두개의 값으로 유니크값이 설정되어 있었다.

그래서 쿼리를 다음과 같이 수정하니 정상적으로 실행되었다.

 

INSERT INTO frame (id, chnl_id, frame_body_cntt, create_at, updated_at) 
    VALUES ('A0016','A','오렌지', now(), now())
    ON CONFLICT (id, chnl_id)
        DO nothing;

 

 

 

끝!

 

참고사항

https://www.postgresql.org/docs/current/sql-insert.html

https://betakuang.medium.com/why-postgresqls-on-conflict-cannot-find-my-partial-unique-index-552327b85e1

https://stackoverflow.com/questions/42022362/no-unique-or-exclusion-constraint-matching-the-on-conflict