SQL UPDATE Statement

The UPDATE statement in SQL is used to modify existing records in a table. You can update one column, multiple columns, or even multiple rows at once, depending on the condition you specify with the WHERE clause.

📌 Syntax

UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;

⚠️ Important: If you omit the WHERE clause, all rows in the table will be updated!

📊 Example Table: users

id | name    | age | city
---+---------+-----+---------
1  | Alice   | 22  | New York
2  | Bob     | 30  | London
3  | Charlie | 18  | Sydney
4  | Diana   | 27  | Toronto
5  | Ethan   | 35  | Paris

🔍 Example 1: Update a Single Column

UPDATE users SET city = 'San Francisco' WHERE name = 'Alice';

🔍 Example 2: Update Multiple Columns

Change both age and city for Bob:

UPDATE users
SET age = 31, city = 'Berlin'
WHERE name = 'Bob';

🔍 Example 3: Update Multiple Rows

Set the city to "Unknown" for all users younger than 20:

UPDATE users
SET city = 'Unknown'
WHERE age < 20;

🔍 Example 4: Update Without WHERE (Dangerous!)

If you run this query, every row will be updated:

UPDATE users
SET city = 'Global';

Use this carefully! In production, always include a WHERE clause unless you truly want to update all rows.

🔍 Example 5: Using Expressions

You can also update using calculations. For example, give everyone a +1 year age increase:

UPDATE users
SET age = age + 1;

⚡ Best Practices

  • Always test your WHERE clause with a SELECT first.
  • Back up important data before large updates.
  • Use transactions for bulk updates to ensure data integrity.
  • Index columns used in WHERE for faster updates.

📝 Summary

The UPDATE statement modifies existing rows in a table. You can update one or many rows, change single or multiple columns, and even use expressions. However, updates without a WHERE can overwrite all rows, so use them carefully!

🚀 Next Steps

In the next lesson, we will cover the SQL DELETE Statement, which allows you to remove records from a table.