How to Update Data in a MySQL Table
Today we will learn about how to modify existing data in a table using the
UPDATE statement. We will see how to use the SET keyword and how to use the
WHERE clause to target specific rows.
Basic Syntax:
UPDATE table_name
SET column1 = value1,
column2 = value2,
...
WHERE condition;
• UPDATE: Specifies the table you want to modify.
• SET: Assigns new values to columns.
• WHERE: Filters which rows should be updated. Always include a WHERE
clause unless you want to update all rows
Update a Single Row:
Eg: Change the grade of student with id = 2 to 12th
UPDATE student
SET grade = '12th'
WHERE id = 2;
Update Multiple Columns:
Eg: Change age to 17 and grade to ‘10th’ for id = 3
UPDATE student
SET age = 17,
grade = '10th'
WHERE id = 3;
Update All Rows:
Eg: Set all students to age 18
UPDATE student
SET age = 18;
Conditional Update with Comparison Operators:
Eg: Promote all students in 9th grade to 10th grade
UPDATE student
SET grade = '10th'
WHERE grade = '9th';
Eg: Increase age by 1 for students younger than 18
UPDATE student
SET age = age + 1
WHERE age < 18;
Update Using IS NULL:
Eg: Set default grade to ‘Unknown’ where grade is NULL
UPDATE student
SET grade = 'Unknown'
WHERE grade IS NULL;