mysql update increment int field that is null
Asked Answered
E

3

19

I have a very large table with two INT columns that are null on Default. This is a problem because since they are INT fields, it would help in many cases if they were originally set to 0.

So my questions are, is there a way I can UPDATE and INCREMENT(+1) these fields while they are like this (null on Default)? BTW.. I didn't have luck so far, it seems increment only works when the default=0

..or is my only option to Change the Default to none from null

Electromotive answered 20/3, 2011 at 7:6 Comment(0)
O
49
UPDATE TableName SET column = IFNULL(column, 0) + 1 WHERE ...

More info on IFNULL. It returns the first argument if it is not NULL, the second otherwise.

Opalina answered 20/3, 2011 at 7:8 Comment(0)
L
3

Try setting the field as NOT NULL to get away with the problem so that default value of 0 is used instead of null. The other option is to set column as zero whenever it is null.

UPDATE TableName SET FieldName = '0' WHERE FieldName IS NULL

Other alternative would be to issue IFNULL to return 0 in case the column is null and then incrementing the column.

UPDATE TableName SET FieldName = IFNULL(FieldName,0) 
Lacee answered 20/3, 2011 at 7:18 Comment(0)
U
0

The SQL standard would be to use COALESCE(); this has been available in MySQL since version 3.23 (which was released into production in 2001):

UPDATE mytable
   SET mycolumn = COALESCE(mycolumn, 0) + 1
 WHERE my_other_columns = ...

I can't see any reason to choose IFNULL() over COALESCE() here.

Hope this helps.

Ungulate answered 1/5, 2018 at 13:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.