SQL
Perform Conditional Updates on Multiple Columns
Learn how to update multiple columns with different values based on various conditions within a single `UPDATE` statement using `CASE` expressions.
UPDATE products
SET
price = CASE
WHEN category = 'Electronics' THEN price * 1.05
WHEN category = 'Books' THEN price * 1.02
ELSE price
END,
stock = CASE
WHEN category = 'Electronics' THEN stock - 10
WHEN category = 'Books' THEN stock - 5
ELSE stock
END,
last_updated = NOW()
WHERE is_active = TRUE;
How it works: This query performs a conditional update on the `products` table. It uses `CASE` expressions within the `SET` clause to apply different price and stock adjustments based on the `category` of each product. For example, 'Electronics' receive a 5% price increase and 10 units reduction in stock, while 'Books' get a 2% price increase and 5 units reduction. The `last_updated` timestamp is also updated for all active products.