SQL
Perform Conditional Updates on Multiple Rows
Learn to update multiple database rows with different values based on specific conditions by utilizing the powerful SQL CASE statement within an UPDATE query.
UPDATE products
SET
price = CASE
WHEN category = 'electronics' THEN price * 1.10 -- Increase by 10%
WHEN category = 'books' THEN price * 0.90 -- Decrease by 10%
ELSE price
END,
updated_at = NOW()
WHERE
stock_quantity > 0;
How it works: This SQL snippet demonstrates how to perform conditional updates on multiple rows using the `CASE` statement within an `UPDATE` query. It allows you to apply different modifications to the `price` column based on the `category` of each product, increasing prices for 'electronics' and decreasing them for 'books'. The `updated_at` column is also set, and the `WHERE` clause ensures only products in stock are considered, offering flexible and powerful bulk update capabilities for dynamic data management.