Computer Science · Ch 9 — Structured Query Language (SQL)
Data Updation
Data Updation
The UPDATE statement is the tool for modifying existing data in a table. You use it when a value in one or more columns of a record needs to be changed — for example, correcting a spelling, updating an address, or filling in a missing value.
The basic syntax is:
UPDATE table_name
SET attribute1 = value1, attribute2 = value2, ...
WHERE condition;
The WHERE clause is critical: it identifies exactly which row(s) should be updated. Without it, the change applies to every row in the table.
Example 1: Updating a single column for one row
In the STUDENT table, the student with roll number 3 has a NULL value in the GUID column. Because students with roll numbers 3 and 5 are siblings, we need to set the GUID for roll number 3 to 101010101010.
mysql> UPDATE STUDENT
-> SET GUID = 101010101010
-> WHERE RollNumber = 3;
Query OK, 1 row affected (0.06 sec)
Rows matched: 1 Changed: 1 Warnings: 0
The message Rows matched: 1 confirms that one row satisfied the WHERE condition. Changed: 1 means the value was actually modified. You can verify the result with SELECT * FROM STUDENT.
If you omit the WHERE clause in the above statement, every student's GUID would be set to 101010101010. Always double-check that your WHERE condition is correct before executing an UPDATE.
Example 2: Updating multiple columns for one row
Suppose the guardian with GUID 466444444666 has requested two changes: the address to 'WZ - 68, Azad Avenue, Bijnour, MP' and the phone number to '9010810547'. You can update both columns in a single UPDATE statement by separating the assignments with commas.
mysql> UPDATE GUARDIAN
-> SET GAddress = 'WZ - 68, Azad Avenue,
-> Bijnour, MP', GPhone = 9010810547
-> WHERE GUID = 466444444666;
Query OK, 1 row affected (0.06 sec)
Rows matched: 1 Changed: 1 Warnings: 0
After the update, the GUARDIAN table looks like this:
| GUID | GName | Gphone | GAddress |
|---|---|---|---|
| 444444444444 | Amit Ahuja | 5711492685 | G-35, Ashok vihar, Delhi |
| 111111111111 | Baichung Bhutia | 3612967082 | Flat no. 5, Darjeeling Appt., Shimla |
| 101010101010 | Himanshu Shah | 4726309212 | 26/77, West Patel Nagar, Ahmedabad |
| 333333333333 | Danny Dsouza | NULL | S -13, Ashok Village, Daman |
| 466444444666 | Sujata P. | 3801923168 | WZ - 68, Azad Avenue, Bijnour, MP |