UPDATE Statement
Modify existing data in your tables with the UPDATE statement.
- Single Column Updates â Change one field at a time
- Multi-Column Updates â Modify several fields simultaneously
- Safe Patterns â Preview changes before committing Always preview with SELECT before running UPDATE.
What Is UPDATE?
UPDATE employees
SET salary = 85000
WHERE id = 1;
Basic Syntax
| Component | Purpose | Required |
|---|---|---|
UPDATE table_name | Specifies the target table | Yes |
SET column = value | Defines columns and new values | Yes |
WHERE condition | Filters which rows to update | No (dangerous) |
-- Update a single column
UPDATE employees
SET email = 'john.doe@company.com'
WHERE id = 101;
-- Update multiple columns
UPDATE employees
SET
first_name = 'Jonathan',
last_name = 'Smith',
email = 'jonathan.smith@email.com',
updated_at = CURRENT_TIMESTAMP
WHERE id = 1234;
Update with Expressions
SET clauses accept expressions, not just literal values. This lets you compute new values from existing data.
-- Give all Engineering employees a 10% raise
UPDATE employees
SET salary = salary * 1.10
WHERE department = 'Engineering';
-- Update using CASE expression
UPDATE products
SET status = CASE
WHEN stock_quantity = 0 THEN 'Out of Stock'
WHEN stock_quantity < 10 THEN 'Low Stock'
ELSE 'In Stock'
END
WHERE category_id = 5;
-- Update using a subquery
UPDATE employees
SET salary = (
SELECT AVG(salary)
FROM employees
WHERE department_id = 3
)
WHERE department_id = 3 AND performance_rating = 'Average';
Safe Update Pattern
Follow a three-step process to avoid accidental data loss: preview, execute, verify.
-- Step 1: Preview affected rows
SELECT * FROM employees WHERE department = 'Engineering';
-- Step 2: Run the update
UPDATE employees
SET salary = salary * 1.10
WHERE department = 'Engineering';
-- Step 3: Verify the changes
SELECT * FROM employees WHERE department = 'Engineering';
BEGIN TRANSACTION;
UPDATE employees
SET status = 'Active'
WHERE last_login_date > DATE_SUB(CURRENT_DATE, INTERVAL 90 DAY);
-- Check affected rows
SELECT ROW_COUNT();
-- COMMIT; -- if satisfied
-- ROLLBACK; -- if something went wrong
Batch Updates
For large datasets, update in batches to avoid long locks and transaction log bloat.
-- Batch 1
UPDATE employees
SET salary = salary * 1.05
WHERE department = 'Sales'
AND employee_id BETWEEN 1000 AND 2000;
-- Batch 2
UPDATE employees
SET salary = salary * 1.05
WHERE department = 'Sales'
AND employee_id BETWEEN 2001 AND 3000;
-- Repeat until all rows are processed
Common Pitfalls
| Pitfall | Consequence | Solution |
|---|---|---|
| Missing WHERE clause | Updates all rows | Always add WHERE |
| Forgetting NULL handling | Unexpected NULL values | Use SET col = COALESCE(val, default) |
| Ignoring constraints | Constraint violation error | Check foreign keys before updating |
| No transaction wrap | Cannot undo mistakes | Use BEGIN/COMMIT/ROLLBACK |
-- Dangerous: Updates ALL rows
UPDATE employees SET salary = 50000;
-- Safe: Targeted update with WHERE
UPDATE employees SET salary = 50000 WHERE department = 'Interns';
Performance Considerations
- Index the WHERE columns â speeds up row lookup
- Batch large updates â reduces lock duration
- Monitor transaction logs â UPDATE generates redo entries
- Use EXPLAIN â verify the query plan before updating
- Minimize column count â only update columns that change
-- Check the execution plan
EXPLAIN UPDATE employees
SET salary = salary * 1.10
WHERE department = 'Engineering';
Practice Exercises
Exercise 1: Write an UPDATE to set all orders older than 30 days to status 'Archived'.
-- Solution
UPDATE orders
SET status = 'Archived'
WHERE order_date < DATE_SUB(CURRENT_DATE, INTERVAL 30 DAY);
Exercise 2: Update multiple columns for a specific employee.
-- Solution
UPDATE employees
SET
first_name = 'Robert',
last_name = 'Brown',
email = 'robert.brown@company.com',
department_id = 5
WHERE employee_id = 456;
Exercise 3: Use a CASE expression to assign discounts based on price.
-- Solution
UPDATE products
SET discount_percentage = CASE
WHEN price > 100 THEN 15
WHEN price > 50 THEN 10
ELSE 5
END
WHERE category = 'Clothing';
Summary
| Operation | Speed | Logging | Reversible |
|---|---|---|---|
| UPDATE | Moderate | Full | Only in transaction |
| DELETE | Moderate | Full | Only in transaction |
| INSERT | Fast | Minimal | No |
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type â Always start by categorizing the problem
- Incorrect formula application â Verify the formula applies to your specific case
- Unit errors â Always check units are consistent throughout
- Sign errors â Pay careful attention to positive and negative values
- Rounding too early â Keep full precision until the final answer
- Forgetting constraints â Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic â Build on the foundation laid here
- Next Topic â See how this concept extends to more advanced material
- Practice Problems â Additional exercises with solutions
- Video Explanation â Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions