tags:

views:

46

answers:

4

We have a column that is a simple integer. We want to add to each row the value 10. How do we do it in sql for the MySQL database?

Actually we have another column that needs to do the same thing, and it is a date. We need to add a month to the date. How to do that?

+7  A: 
 UPDATE table_name SET column_value = column_value + 10;
Jamie Wong
what about for a date? Adding a month?
erotsppa
That depends on what kind of column you're storing. Is it an integer storing a timestamp, is it a datetime, is it a date? Do you want to add 10 seconds to the count, 10 hours, 10 days, what?
Jamie Wong
if column value is null it will not add 10 to it
Salil
+2  A: 
update table_name set column_name=column_name+10 where column_name is not null;
Salil
What will happen if the field is already null? Will the value become 10, or will it throw an error?
Jamie Wong
@Jamie: It won't update columns that are null.
Josh K
if column value is null it will not add 10 to it
Salil
@Salil Sorry, what I meant to say is, if you were to omit the `WHERE column_name IS NOT NULL` portion of your query, what would happen. I understand that your query would prevent this occurrence completely.
Jamie Wong
+2  A: 

Should be something simple like this:

UPDATE some_table SET int_field = int_field + 10
Paul Sasik
+5  A: 

Integers:

UPDATE table_name SET int_column_value = int_column_value + 10;
UPDATE table_name SET int_column_value = 10 WHERE int_column_value IS NULL;

Dates:

UPDATE table_name SET date_column_value = DATEADD(date_column_value, INTERVAL 1 MONTH);

More info: http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_adddate

HorusKol
I was wondering how you'd go about that for dates. Cool.
Jamie Wong