0

Consider the following table(T) in mysql.

id c1  c2
1  10  100
2  20  200
3  30  300

Suppose I want to update "c1" of the row with id=2. I can do the following.

UPDATE T set col1=20 where id=1;

Suppose I want bulk update.

INSERT INTO T(id,c1) VALUES (1,20),(2,40) ON DUPLICATE KEY UPDATE c1=VALUES(c1);

But this will give you an error if default value for "c2" is not set in the SCHEMA.

Is there another way to achieve the task?

aydinugur
  • 1,208
  • 2
  • 14
  • 21
Avinash142857
  • 129
  • 2
  • 13

1 Answers1

1

The error happens when you INSERT a value for the first time, meaning there's no duplicate key to update. Your c2 column is not nullable and has no default value. To fix this either

  • make c2 nullable or
  • provide a default value for c2 or
  • provide a value for c2 in your insert statement

When you don't want to insert into the table, insert the values into a temporary table, then use an update statement and join the two tables.

fancyPants
  • 50,732
  • 33
  • 89
  • 96