🗄️SQL Templates
UPDATE Data Patterns
Update existing records with WHERE conditions and multiple columns
Explanation
Modify existing database records safely using UPDATE with proper WHERE clauses.
Examples
Update single column
Input
UPDATE users SET status = "active"
Output
Updates status for matching rows
Update with WHERE
Input
UPDATE users SET status = "active" WHERE id = 1
Output
Updates only user with id 1
Code Examples
SQL
-- Update single column
UPDATE users
SET status = 'active'
WHERE id = 1;
-- Update multiple columns
UPDATE users
SET
status = 'active',
verified = true,
updated_at = NOW()
WHERE id = 1;
-- Update with condition
UPDATE orders
SET status = 'completed'
WHERE payment_status = 'paid'
AND shipped_at IS NOT NULL;
-- Update from calculation
UPDATE products
SET discounted_price = price * 0.9
WHERE category = 'electronics';
-- Update with JOIN (PostgreSQL/MySQL)
UPDATE users u
INNER JOIN orders o ON u.id = o.user_id
SET u.last_order_date = o.created_at
WHERE o.id IN (
SELECT MAX(id)
FROM orders
GROUP BY user_id
);
-- Conditional update with CASE
UPDATE users
SET status = CASE
WHEN last_login > NOW() - INTERVAL '30 days' THEN 'active'
WHEN last_login > NOW() - INTERVAL '90 days' THEN 'inactive'
ELSE 'dormant'
END;
-- Update and return (PostgreSQL)
UPDATE users
SET status = 'active'
WHERE id = 1
RETURNING *;
-- Increment counter
UPDATE products
SET view_count = view_count + 1
WHERE id = 123;
-- Update all rows (BE CAREFUL!)
UPDATE users
SET notification_enabled = true;
-- Safe update with LIMIT (MySQL)
UPDATE users
SET status = 'migrated'
WHERE status = 'legacy'
LIMIT 100;💡 Tips
- ALWAYS use WHERE clause (unless updating all rows)
- Test with SELECT before UPDATE
- Use transactions for multiple updates
- Add updated_at timestamp tracking
- Use CASE for conditional updates
- Backup before large updates
- Use LIMIT for batch updates in MySQL
⚠️ Common Pitfalls
- Forgetting WHERE updates ALL rows!
- Concurrent updates can cause race conditions
- Update without transaction can be partial
- NULL comparison requires IS NULL, not = NULL
- Updating primary/foreign keys breaks relationships
- Large updates can lock tables