Write a query to update a column based on a condition

Description: Add 5 marks to every student who has less than 50 marks.

Tables: the exercises use the students (id, name, city, marks, course_id) and courses (id, course_name) tables, with the data from our MySQL INSERT chapter. The students are: Robin (Delhi, 85), Maria (Mumbai, 92), John (Pune, 78), Asha (Jaipur, 88), Vikram (Delhi, 65), Neha (Mumbai, 45).

Hint:

  • Use UPDATE ... SET ... WHERE.
  • The new value can use the old value: marks + 5.

MySQL query to update a column with a condition

UPDATE students
SET marks = marks + 5
WHERE marks < 50;

SELECT name, marks FROM students WHERE name = 'Neha';

Output:

Tutorials Class - Output Window
name marks
Neha 50

How it works

  • Only Neha has less than 50 marks, so only her row is changed (45 + 5 = 50).
  • Without WHERE all rows would change.
  • To restore the data: UPDATE students SET marks = 45 WHERE name = 'Neha';

Read MySQL UPDATE.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.