SQL
Conditionally Update Multiple Records with CASE
Update multiple rows with different values based on specific conditions within a single SQL UPDATE statement using the powerful CASE expression.
UPDATE users
SET status = CASE
WHEN last_login < '2023-01-01' THEN 'inactive'
WHEN email_verified = FALSE THEN 'pending_verification'
ELSE 'active'
END,
updated_at = NOW()
WHERE id IS NOT NULL; -- Or a more specific WHERE clause to target relevant users
How it works: This `UPDATE` statement modifies the `status` and `updated_at` columns for users based on various conditions. The `CASE` expression allows you to define different `status` values depending on whether `last_login` is before a certain date or `email_verified` is false. This is highly useful for batch processing and conditional data management, allowing for complex updates in a single query.