Here is my table:

FieldA   FieldB  FieldC
  1        3
  4        2
  7        8
  9        6

I want to update FieldC with the minimum value of FieldA and FieldB. I did it like this:

update mytable 
set FieldC=FieldA where FieldA < FieldB

update mytable set FieldC=FieldB where FieldB < FieldA

Can we do this with only one update query? Thanks.

    Requires Free Membership to View

The answer is yes, but with a caveat.

update mytable 
set FieldC = case when FieldA < FieldB
                  then FieldA
                  else FieldB end

Note that this will actually update FieldC. Your two queries would result in FieldC not being updated when FieldA happens to equal FieldB.

However, there should be no need to do this. You can use that same CASE expression in any query where you would wish to use FieldC. It's usually not a good idea to store data which can be derived like that. Yes, there are exceptions, but this isn't one of them because it's too simple.

Be careful extending this to more than two columns. It may be that you have not normalized your table properly. See my earlier answer Highest value in each row (17 May 2004) for a more complex example.

This was first published in October 2006

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: