I have a question regarding SQL syntax and whether or not a particular action is possible in a single query. Consider the following example:
Let’s say we have a Recipe table. Every recipe has 5 ingredients listed under columns ingredient1, ingredient2, etc. Let’s also say that suddenly sugar is determined to be unhealthy for you and every Recipe must replace ‘sugar’ with ‘artificial sweetener’ in every ingredient column where it exists. The problem I’ve run into is that there is no Ingredient table, thus every ingredient is listed literally under one of five columns rather than reference something like an ingredient ID.
How can I write the following (pseudo) query, if possible?
UPDATE Recipe
(SET ingredient1 = 'artificial sweetener' WHERE ingredient1 = 'sugar') OR
(SET ingredient2 = 'artificial sweetener' WHERE ingredient2 = 'sugar') OR
(SET ingredient3 = 'artificial sweetener' WHERE ingredient3 = 'sugar') OR
(SET ingredient4 = 'artificial sweetener' WHERE ingredient4 = 'sugar') OR
(SET ingredient5 = 'artificial sweetener' WHERE ingredient5 = 'sugar')
I have found multiple articles online about setting a column to a certain value based on its current value, but not for only setting (specific) columns that contain a value. Any help is greatly appreciated.
A CASE expression will dictate whether each of the five columns need to be modified. Use a WHERE clause to filter out any rows that don’t require modification: