SQL

Performing Conditional Updates with CASE WHEN

Learn how to update multiple rows with different values based on specific conditions within a single SQL UPDATE statement using the powerful CASE WHEN clause.

UPDATE products
SET
    price = CASE
        WHEN category_id = 1 THEN price * 1.10 -- Increase price by 10% for category 1
        WHEN category_id = 2 THEN price * 1.05 -- Increase price by 5% for category 2
        ELSE price -- Keep original price for other categories
    END,
    last_updated_at = NOW()
WHERE
    category_id IN (1, 2, 3); -- Apply to relevant categories
How it works: This SQL snippet demonstrates how to perform conditional updates on a table. The `CASE WHEN` statement allows you to specify different update actions for a column (`price` in this example) based on various conditions (`category_id`). If `category_id` is 1, the price increases by 10%; if 2, it increases by 5%. For other categories, the price remains unchanged. The `WHERE` clause can further narrow down the rows affected by the update.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs