🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

UPDATE Statement

SQL FundamentalsDMLđŸŸĸ Free Lesson
SQL Fundamentals

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 Flow: Safe Three-Step ProcessStep 1: PreviewSELECT * FROM employeesWHERE dept = 'Eng';Check affected rowsStep 2: ExecuteUPDATE employeesSET salary = 85000WHERE dept = 'Eng';Modify dataStep 3: VerifySELECT * FROM employeesWHERE dept = 'Eng';Confirm changesWarning: Omitting WHERE updates ALL rows!
UPDATE employees
SET salary = 85000
WHERE id = 1;

Basic Syntax

ComponentPurposeRequired
UPDATE table_nameSpecifies the target tableYes
SET column = valueDefines columns and new valuesYes
WHERE conditionFilters which rows to updateNo (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

PitfallConsequenceSolution
Missing WHERE clauseUpdates all rowsAlways add WHERE
Forgetting NULL handlingUnexpected NULL valuesUse SET col = COALESCE(val, default)
Ignoring constraintsConstraint violation errorCheck foreign keys before updating
No transaction wrapCannot undo mistakesUse 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

  1. Index the WHERE columns — speeds up row lookup
  2. Batch large updates — reduces lock duration
  3. Monitor transaction logs — UPDATE generates redo entries
  4. Use EXPLAIN — verify the query plan before updating
  5. 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

OperationSpeedLoggingReversible
UPDATEModerateFullOnly in transaction
DELETEModerateFullOnly in transaction
INSERTFastMinimalNo

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

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. 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

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. 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

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids 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
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert SQL Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement