tags:

views:

34

answers:

3

updaten some_table set one_field=xxx, another_field=(only update in condition, ex. large then zero then minus one).

+8  A: 

Use a CASE to either update the field to a new value or to set the same value again depending on the value of the condition.

UPDATE some_table
SET one_field = 'xxx',
    another_field = CASE WHEN another_field > 0
                         THEN another_field - 1
                         ELSE another_field
                    END

For decrementing a number that is not allowed to go below zero you could use GREATEST:

UPDATE some_table
SET one_field = 'xxx',
    another_field = GREATEST(0, another_field - 1)
Mark Byers
the GREATEST function is exactly what i'm looking for. thank you.
lovespring
+1  A: 
update sone_table set one_field=xxx, another_field=IF(another_field > 0, value ,  another_field) 
Bogdan Constantinescu
hi, Bogdan, what's the diff with Mark Byers's answer?
lovespring
I tend to not like `cases`. Also seems shorter to me :) PS: thank you haim, I forgot the last field when I submited the response!
Bogdan Constantinescu
A: 
Josaph
Mark posted while I was composing. His answer would be more inline. The above example gives you more control over the conditionals. Either way works; but his is probably what you are looking for.
Josaph