πŸŽ‰ 75% of content is free forever β€” Unlock Premium from $10/mo β†’
CW
Search courses…
πŸ’Ό Servicesℹ️ Aboutβœ‰οΈ ContactView Pricing Plansfrom $10

UPDATE Statement

SQL FundamentalsDML🟒 Free Lesson

Advertisement

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?

DfUPDATE Statement

The UPDATE statement modifies existing records in a table. It locates rows using a WHERE condition, then changes column values as specified in the SET clause. Without WHERE, all rows are updated.

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;
Omitting the WHERE clause updates every row in the table. Always include WHERE unless you intentionally want to update all records.

Basic Syntax

DfUPDATE Syntax

UPDATE table_name SET column1 = value1, column2 = value2 WHERE condition; The WHERE clause is optional but strongly recommended.

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.

DfExpression in SET

A SET expression can reference the current column value, use functions, or combine multiple columns. The expression is evaluated once per matched row.

-- 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';
Subqueries in UPDATE are evaluated once. The result is applied to all matched rows, not recalculated per row.

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';

DfTransaction Safety

Wrapping UPDATE in a transaction allows rollback if the result is unexpected. Use BEGIN TRANSACTION, run the UPDATE, inspect the result, then COMMIT or ROLLBACK.

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.

DfBatch Update

A batch update processes rows in chunks using a range condition (e.g., BETWEEN). This limits lock scope and keeps transaction logs manageable.

-- 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
Each batch should affect no more than 10,000–50,000 rows depending on your database engine and lock settings.

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

DfUPDATE Performance

UPDATE performance depends on WHERE clause indexing, row count, and transaction logging. Indexed WHERE columns allow the database to locate rows quickly without full table scans.

  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

Key Takeaways

  1. UPDATE modifies existing records in a table
  2. Always include a WHERE clause unless updating all rows intentionally
  3. Preview with SELECT before running UPDATE
  4. You can update multiple columns and use expressions
  5. Use transactions for safety on critical updates
  6. Batch large updates to avoid long locks and log bloat
OperationSpeedLoggingReversible
UPDATEModerateFullOnly in transaction
DELETEModerateFullOnly in transaction
INSERTFastMinimalNo
⭐

Premium Content

UPDATE Statement

Unlock this lesson and 900+ advanced tutorials with a Premium plan.

🎯End-to-end Projects
πŸ’ΌInterview Prep
πŸ“œCertificates
🀝Community Access

Already a member? Log in

Need Expert SQL Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement