DEV Community

Le Vuong
Le Vuong

Posted on • Edited on

1

Using INSERT ON CONFLICT as an alternative to Upsert in Postgres

Wanna try another way to "Upsert" (update or insert) without using the upsert query? Modify your insert query to include the on conflict clause.

However, Postgres may produce "No unique or exclusion constraint" error if you don't define the unique constraint satisfying some of it conditions (if your unique index is a partial one, the predicates you added to CREATE INDEX must be all provided in on conflict clause).

Please notice the where clauses in 2 queries below:

CREATE UNIQUE INDEX uniq_idx_company_personnel
  ON person(company_id, personnel_no) WHERE company_id > 0;
Enter fullscreen mode Exit fullscreen mode
INSERT INTO person (company_id, personnel_no, name)
  VALUES (1, 1, "Boss")
  ON CONFLICT (company_id, personnel_no) WHERE company_id > 0
    DO UPDATE SET name = EXCLUDED.name;
Enter fullscreen mode Exit fullscreen mode

Please see detailed explanation on how to use the Insert with "on conflict" and how to avoid "No unique or exclusion constraint" error in this interesting post.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay