Update Query in MySQL
Introduction
After inserting data into a table, you may need to modify existing records.
In MySQL, this is done using the UPDATE query.
The UPDATE statement allows you to change values in one or more columns for specific rows.
What is an UPDATE Query
The UPDATE statement is used to modify existing data in a table.
It does not create new rows — it only updates existing ones.
Basic Syntax
UPDATE table_name
SET column1 = value1, column2 = value2
WHERE condition;
Example
UPDATE Students
SET age = 21
WHERE id = 1;
This updates the age of the student with id = 1.
Update Multiple Columns
UPDATE Students
SET name = 'Rahul Sharma', age = 22
WHERE id = 1;
Update Multiple Rows
UPDATE Students
SET city = 'Delhi'
WHERE age > 20;
This updates all students with an age greater than 20.
Update All Rows
UPDATE Students
SET status = 'Active';
⚠️ This updates all rows in the table.
Using Conditions (WHERE)
The WHERE clause is very important.
Without WHERE:
- All rows will be updated
- Data may be changed unintentionally
Using Expressions in UPDATE
UPDATE Students
SET age = age + 1;
This increases the age for all students.
Using LIMIT
UPDATE Students
SET city = 'Mumbai'
LIMIT 2;
Updates only 2 rows.
Example Scenario
Suppose a student changes cities:
UPDATE Students
SET city = 'Bangalore'
WHERE id = 2;
Common Mistakes
- Forgetting WHERE clause
- Updating wrong rows
- Using incorrect column names
- Not testing queries before execution
Key Points to Remember
- UPDATE modifies existing data
- Always use WHERE for safety
- Can update single or multiple rows
- Supports expressions and conditions
- Changes are permanent