To increase the marks of all section B students by 5
Expt. No.33
Page No.66
Add 5 marks to section B (UPDATE)
Aim
To increase the marks of every student in section B by 5 and display the changed rows.
Concepts used
Queries
USE school;UPDATE student SET marks = marks + 5 WHERE section = 'B';SELECT rno, name, section, marks FROM student WHERE section = 'B';
A marked line continues the line above it. In your file, write it on the same line.
Table used
Table: student
+-----+-------+---------+--------+--------+------------+-------+ | rno | class | section | gender | name | dob | marks | +-----+-------+---------+--------+--------+------------+-------+ | 1 | XI | A | F | Aarohi | 2009-03-14 | 78 | | 2 | XI | A | M | Bharat | 2008-11-02 | 45 | | 3 | XI | B | M | Chetan | 2009-07-21 | NULL | | 4 | XI | B | F | Divya | 2009-01-30 | 91 | | 5 | XII | A | M | Eshan | 2008-05-17 | 66 | | 6 | XII | A | F | Fatima | 2008-09-09 | 83 | | 7 | XII | B | M | Gagan | 2007-12-25 | 38 | | 8 | XII | B | F | Hina | 2008-02-11 | NULL | | 9 | XI | A | M | Ishan | 2009-10-05 | 57 | | 10 | XII | A | F | Jaya | 2008-06-28 | 74 | +-----+-------+---------+--------+--------+------------+-------+
Output
mysql> USE school;
Database changed
mysql> UPDATE student SET marks = marks + 5 WHERE section = 'B';
Query OK, 2 rows affected
mysql> SELECT rno, name, section, marks FROM student WHERE section = 'B';
+-----+--------+---------+-------+
| rno | name | section | marks |
+-----+--------+---------+-------+
| 3 | Chetan | B | NULL |
| 4 | Divya | B | 96 |
| 7 | Gagan | B | 43 |
| 8 | Hina | B | NULL |
+-----+--------+---------+-------+
4 rows in set
✓ Printed by running this query set, not typed by hand.
Result
UPDATE reported 2 rows affected although section B has 4 students: Divya went from 91 to 96 and Gagan from 38 to 43, but Chetan and Hina stayed NULL, because NULL + 5 is still NULL.
Viva voce: what the examiner may ask
01What happens if the WHERE clause is left out of UPDATE?
Every row in the table is changed.
02Why did only 2 rows change?
NULL + 5 is NULL, so the two NULL rows did not actually change.
03How do you change two columns in one UPDATE?
Separate them with commas: SET marks = 90, section = 'A'.
Variations for the lab test
- Set the marks of roll number 3 to 64.
- Move all class XII section B students to section A.
- Decrease the marks of students who scored above 90 by 2.
! Common mistake Forgetting WHERE:
UPDATE student SET marks = marks + 5; changes every student.