SQL

Perform Conditional Updates Using CASE Statements

Update multiple rows in a table with different values based on specific conditions within a single SQL statement, enhancing data manipulation flexibility.

UPDATE products
SET
    price = CASE
        WHEN category = 'Electronics' THEN price * 1.05
        WHEN category = 'Books' THEN price * 0.90
        ELSE price
    END,
    last_updated = CURRENT_TIMESTAMP
WHERE
    category IN ('Electronics', 'Books');
How it works: This snippet demonstrates how to perform conditional updates using a `CASE` statement within an `UPDATE` query. The `price` column is updated differently based on the `category` value. For 'Electronics', the price increases by 5%; for 'Books', it decreases by 10%. The `last_updated` column is also set to the current timestamp for all affected records.

Need help integrating this into your project?

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

Hire DigitalCodeLabs