SQL
Perform Conditional Updates on Table Records
Update multiple fields or apply different values based on specific conditions within a single SQL UPDATE statement, enhancing data management flexibility.
UPDATE products
SET
status = CASE
WHEN quantity = 0 THEN 'Out of Stock'
WHEN quantity < 10 THEN 'Low Stock'
ELSE 'In Stock'
END,
updated_at = NOW()
WHERE category_id = 1;
How it works: This `UPDATE` statement uses a `CASE` expression to set the `status` of products based on their `quantity`. If `quantity` is 0, status becomes 'Out of Stock'; if less than 10, 'Low Stock'; otherwise, 'In Stock'. The `updated_at` column is also updated. This allows for complex, multi-condition updates within a single, efficient query.