SQL
Performing Conditional Updates in a Single SQL Query
Learn to update multiple columns with different values based on specific conditions within a single SQL `UPDATE` statement using the `CASE` expression.
UPDATE users
SET
status = CASE
WHEN last_login < CURRENT_DATE - INTERVAL '90 days' THEN 'inactive'
ELSE 'active'
END,
premium_status = CASE
WHEN subscription_end_date > CURRENT_DATE THEN TRUE
ELSE FALSE
END,
updated_at = NOW()
WHERE
id IN (1, 2, 3); -- Or other relevant filter
How it works: This snippet demonstrates how to perform conditional updates on multiple columns within a single `UPDATE` statement using the `CASE` expression. This allows different values to be assigned to a column based on various conditions, making the query highly flexible and efficient for batch updates that depend on existing data states.