0

lets say i have table like this (new_table) (all field is not-null constraints):

id    name        km_unit
1     honda       1000
2     toyota      2000
3     bmw         1000
4     wuling      1500

i want to update the table with insert with this query:

insert into new_table(id,km_unit) values
(1,20000),
(2,20000),
(3,200000),
(4,200000)
ON CONFLICT (id) 
DO 
   update SET km_unit = EXCLUDED.km_unit 

but it return error like this :

null value in column "name" violates not-null constraint

the question is how to update the existing km_unit field if the id is same with values that i inserted? can i update the table without writing name field in the values?

1
  • 1
    Your error has nothing to do with the UPDATE part. You are trying to insert rows with a NULL value for the name column, but you have a not null constraint on that column. If you only want to update the rows use an UPDATE statement. Commented Aug 5, 2021 at 8:48

2 Answers 2

3

It seems you don't actually want to insert anything, so use an UPDATE statement:

update new_table dl
  set km_unit = v.km_unit
from (
  values 
    (1,20000),
    (2,20000),
    (3,200000),
    (4,200000)
) as v(id, km_unit)
where v.id = dl.id
Sign up to request clarification or add additional context in comments.

2 Comments

@a_horse_with_no_name . . . But why would the code in the question generate a NOT NULL violation. No rows are being inserted.
@GordonLinoff I assume because it first tries to insert the rows and the NOT NULL check is done before the unique constraint check.
2

NOT NULL constraint

When the NOT NULL constraint is defined for a column, a row containing the null value in that column cannot be added, nor can a row be updated so as to set the null value in that column. A column for which the NOT NULL constraint is defined must have a definite value in every row. An attempt to set the null value in such a column results in a constraint violation.

In your case it means the column NAME should have a value.

2 Comments

can i use the existing values in the tabel without typing it all, like this: on conflict (id) update set name = new_table.name, km_unit = excluded.km_unit
I don't think so. ON CONFLICT works to guarantee UNIQUE ENTRY and has nothing to do with NOT NULL. But you can ALTER your NAME column and set a DEFAULT VALUE for it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.