11

I need to change a few values on my DB.

I forgot to set nullable to the table and it set to 0000-00-00 00:00:00 by default.

Now I need to convert that value in NULL.

The field type is Datetime.

How can I do it?

I try with the typical Update table set field = NULL WHERE field = '0000-00-00 00:00:00'; but it doesn't work.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Borja Pombo
  • 525
  • 1
  • 7
  • 30

5 Answers5

14

You need to first make the column nullable:

ALTER TABLE mytable MODIFY COLUMN field DATETIME NULL;

And then update the values:

UPDATE mytable SET field = NULL WHERE field = '0000-00-00 00:00:00';
Mureinik
  • 297,002
  • 52
  • 306
  • 350
11

From MySQL 5.7, SQL mode NO_ZERO_DATE makes this update impossible unless you firstly disable this restriction (for the duration of the transaction only).

SET sql_mode=(SELECT REPLACE(@@sql_mode,"NO_ZERO_DATE", ""));
UPDATE mytable SET field = NULL WHERE field = '0000-00-00 00:00:00';
Lorenz Meyer
  • 19,166
  • 22
  • 75
  • 121
AlterPHP
  • 12,667
  • 5
  • 49
  • 54
4

You need to first make the column nullable:

@Mysql5.7

Wrong :

update episodes set `ending` = NULL WHERE `ending` = '0000-00-00'

Correct :

update episodes set `ending` = NULL WHERE `ending` = 0000-00-00

Note: Remove the quote from the date value in your where clause. Hope it help someone

Michaël Azevedo
  • 3,874
  • 7
  • 31
  • 45
A. Sideeq
  • 57
  • 1
  • 3
0

Unfortunately this will not work.
for:

update episodes set `ending` = NULL 
WHERE `ending` = '0000-00-00'

If 0000-00-00 is in the where clause, you get the error:

"1292 - Incorrect datetime value: '0000-00-00' for column 'ending' at row 1".

even if ending has NULL and default=null in field definition.

Jan Pfeifer
  • 2,854
  • 25
  • 35
  • This is an older question: If your answer is due to using a much newer version of mySQL software than state version number in your answer. Now it looks silly because the correct/best answer was given more than2 years ago. – ZF007 Feb 04 '18 at 17:07
0

What worked for me is:

  1. Set the field from datetime to varchar(191).
  2. Update all rows with field = '0000-00-00 00:00:00' to NULL.
  3. Set the field back to datetime.
JuliaJ
  • 79
  • 7