← Back to MySQL Course | Chapter 7: Updating & Deleting | Lesson 1 of 4

UPDATE Statement

Introduction to UPDATE

The UPDATE statement lets you change existing records in a table, such as correcting a customer's shipping address. It helps you modify values that are already saved without deleting and re-inserting the row. Always use a WHERE clause to target specific rows, or every row in the table will change.

Example: Introduction to UPDATE

sql
UPDATE customers SET address = '123 New St' WHERE id = 1;

The Importance of the WHERE Clause

The WHERE clause specifies which records should be updated, exactly like it does in a SELECT. If you omit the WHERE clause, all records in the table will be updated. This can accidentally overwrite all your database data, so it's worth running the same WHERE as a SELECT first to preview the affected rows.

Example: The Importance of the WHERE Clause

sql
UPDATE customers SET status = 'inactive'; -- updates ALL rows, no WHERE clause

Updating with Expressions

You can update a column using its current value, such as UPDATE products SET stock = stock - 1. This is useful for incrementing numbers or appending text. MySQL calculates the expression for each row dynamically, using that row's own existing value.

Example: Updating with Expressions

sql
UPDATE products SET stock = stock - 1 WHERE id = 1;

Updating with NULL Values

You can clear a column's value by setting it to NULL, such as removing a scheduled deletion date once it's cancelled. This works only if the column is allowed to hold NULL values (not defined as NOT NULL). It is useful for resetting fields back to an empty, unknown state.

Example: Updating with NULL Values

sql
UPDATE tasks SET scheduled_deletion = NULL WHERE id = 1;

Limiting the Update

You can use the LIMIT clause to restrict the number of updated rows, capping a batch update at a fixed size. This is helpful for updating records in smaller batches. It prevents performance issues and long table locks on very large tables.

Example: Limiting the Update

sql
UPDATE products SET discontinued = 1 LIMIT 10;

⚠️ This is MySQL-specific syntax. It cannot run in the browser editor. Practice this on your local MySQL installation.

🔒

Chapter Quiz — Complete all 4 topics to unlock

0/4 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.