← Back to all snippets
SQL

Performing Conditional Updates with SQL CASE Statements

Update multiple rows with different values based on specific conditions within a single SQL statement. Streamline complex data modifications efficiently.

UPDATE products
SET
    price = CASE
        WHEN category = 'Electronics' THEN price * 1.05
        WHEN category = 'Books' THEN price * 0.90
        ELSE price * 1.02 -- Default price increase for other categories
    END,
    last_updated_at = NOW()
WHERE
    category IN ('Electronics', 'Books', 'Clothing');
How it works: The `UPDATE` statement combined with a `CASE` expression allows for conditional modifications to rows. Instead of writing multiple `UPDATE` statements, this single query adjusts product prices differently based on their `category`. For 'Electronics', price increases by 5%; for 'Books', it decreases by 10%; and for other categories listed in the `WHERE` clause, it increases by 2%. It also updates a timestamp for tracking.

Need help integrating this into your project?

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

Hire DigitalCodeLabs