I am using on conflict clause for insert query like this:
insert into "public"."tbl" ("id", "col1", "col2") values ($1, $2, $3) on conflict ("id") do update set "id" = $4,"col1" = $5,"col2" = $6 returning "id"
and I am getting this error:
null value in column "col3" of relation "tbl" violates not-null constraint
which doesn’t make sense, because even thos col3 has NOT NULL constraint, I am not passing it in the insert query at all, so Postgres should just take it from the existing record, which certainly does not have a null value.
Am I misunderstanding how conflict works? Do I need to pass all columns in the query? If so, there is not point in using insert .. on conflict
because it does not provide any benefit compared to separate insert / update calls.
2
Answers
You must pass col3 into insert which obviously cannot be NULL, your error is not about conflict.
demo at db<>fiddle
merge
:If you’re on PostgreSQL 17, you can even keep the
returning
clause.not null
constraint:update
because you expect zero non-conflicting rows, use an actualupdate
. The nice thing aboutmerge
is you can