Quick Answer
Using UPDATE to change data
Understanding the Issue
The UPDATE statement modifies existing data in table rows. Always use WHERE to target specific rows, unless updating all rows intentionally.
The Problem
This code demonstrates the issue:
Sql
Error
-- Problem: Need to change prices
SELECT * FROM products WHERE category = 'Electronics'; -- Old prices
The Solution
Here's the corrected code:
Sql
Fixed
-- Solution 1: Update specific rows
UPDATE products
SET price = price * 1.1
WHERE category = 'Electronics';
-- Solution 2: Update multiple columns
UPDATE employees
SET salary = salary * 1.05,
last_raise = CURRENT_DATE
WHERE department = 'Engineering';
-- Solution 3: Update with JOIN
UPDATE orders o
JOIN customers c ON o.customer_id = c.customer_id
SET o.priority = 'High'
WHERE c.vip = 1;
Key Takeaways
Always include WHERE clause unless updating all rows.