MySQL UPDATE Query

UPDATE changes the data of existing rows.

UPDATE students
SET marks = 70
WHERE name = 'Vikram';
MySQL says

Query OK, 1 row affected (0.01 sec)
Rows matched: 1 Changed: 1 Warnings: 0

SELECT name, marks FROM students WHERE name = 'Vikram';
Result
name marks
Vikram 70

Note: Never forget WHERE. UPDATE students SET marks = 0; changes every row of the table. Test your WHERE with a SELECT first.

Update many columns

UPDATE students
SET city = 'Pune', marks = 72
WHERE id = 5;

Calculate the new value

UPDATE students
SET marks = marks + 5
WHERE city = 'Mumbai';
MySQL says

Query OK, 2 rows affected (0.01 sec)
Rows matched: 2 Changed: 2 Warnings: 0

Both Mumbai students got 5 more marks.


Put the data back

The next chapters use the original data, so restore it with these commands.

UPDATE students SET city = 'Delhi', marks = 65 WHERE id = 5;
UPDATE students SET marks = marks - 5 WHERE city = 'Mumbai';

You can also read how this is done from Python.


Summary

  • UPDATE table SET column = value WHERE condition;
  • Without WHERE all rows change.
  • Next: DELETE.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.