SQL
Perform Multi-Column Conditional Update with CASE
Learn to update multiple columns in a single SQL statement based on different conditions using the powerful CASE expression for flexible data manipulation.
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
status = 'active';
How it works: This query demonstrates how to update multiple columns, 'price' and 'last_updated', in a single UPDATE statement. It uses a CASE expression to apply different price adjustments based on the 'category' of the product, allowing for sophisticated conditional logic within the update operation. The 'last_updated' column is set unconditionally to the current timestamp for all products meeting the 'WHERE' clause, ensuring accurate metadata for updated records.