3

In table Colors, there is a Color column. I need to make 5 updates to the values in this column based on different conditions.

SET Color = 'Blue' WHERE Color = 'blue'  
SET Color = 'Green' WHERE Color = 'green'  
SET Color = 'Yellow' WHERE Color = 'yellow'  
SET Color = 'Brown' WHERE Color = 'brown'  
SET Color = 'Orange' WHERE Color = 'orange'

Can I make these 5 updates to the table in one query?

Note: my real values are more complex than this, so disregard simple functions to make the values uppercase

1
  • i dont think so it's possible, you should write separate queries Dec 16, 2016 at 4:41

2 Answers 2

5

You can make use of CASE expression and decide which value you want to set to Color.

UPDATE [YourSchema].[Colors] 
SET     Color=  CASE  
                        WHEN Color = 'blue'  THEN 'Blue' 
                        WHEN Color = 'green'  THEN 'Green' 
                        WHEN Color = 'yellow'  THEN 'Yellow' 
                        WHEN Color = 'brown'  THEN 'Brown' 
                        WHEN Color = 'orange'  THEN 'Orange' 
                    END
 WHERE Color IN ('blue', 'green', 'yellow', 'brown', 'orange') 

Note: If you are having default schema then use dbo.Colors as the table name,

2
  • 1
    You should probably add on a WHERE clause so the UPDATE only acts on records containing colors which should be modified. Dec 16, 2016 at 4:45
  • @TimBiegeleisen Oops.. thanx.. Updated my answer. Dec 16, 2016 at 4:47
2

As an alternative to a lengthy CASE expression, you can simply do a conditional uppercasing of the first letter of a color should that color match the ones you gave in your list.

update Colors
set Color = upper(substr(Color, 1, 1)) || substr(Color, 2)
where Color in ('blue', 'green', 'yellow', 'brown', 'orange')
2
  • Perfect for this situation - I was really looking for an answer I could apply to more complex values (not just updating values for upper/lower case)
    – Chicowitz
    Dec 16, 2016 at 4:46
  • 1
    @Chicowitz Then a CASE expression might serve you better in general, but this query fits your current question well. Dec 16, 2016 at 4:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.