Updating Rows
Data goes out of date. A student moves city, a mark is corrected, a teacher is promoted. update changes values in rows that are already there — and it comes with the most expensive single-word mistake in this whole course.
1The syntax
update <table name> set <column> = <value> where <condition>;
Three parts, and each answers a different question:
Which table?
What is the new value?
Which rows?
The examples below run against a small four-row copy of the students table, so that every change is easy to follow:
2Changing one value in one row
Asha's city was never recorded. Fill it in:
where found. Changed is how many actually ended up different. A row that already held the new value is matched but not changed.3Changing several columns at once
One set, then as many column = value pairs as you like, separated by commas. There is no second set:
Both columns changed, one row was touched, and it took one trip to the server.
4Forgetting the where
The where clause is optional. That is the problem. Leave it out and the update is applied to every row in the table:
Ravi was from Gangtok, Tom from Kolkata, Asha from Namchi. All three are now from Singtam, and the original values are gone for good. There was no warning and no confirmation — the query was perfectly valid, it just did not mean what was intended.
Read the counts once more: Rows matched: 4 but Changed: 3. All four rows were selected, but Veena was already from Singtam, so hers did not actually change. That is the distinction from section 2, visible in real output.
update, run the same where as a select first:select * from students where id = 4001;Whatever rows come back are exactly the rows your update will change. If that is twelve rows and you expected one, you have just saved yourself.
5When the where matches nothing
No error — the query worked, it simply found no rows to work on:
Rows matched: 0 is the tell. If you expected to change something and see this, the condition is wrong — a mistyped id, or the wrong quotes around a value — not the set.
6Recap
Changes existing rows. It never adds or removes any.
One set, then comma-separated pairs. Not one set each.
Valid SQL, no warning, no undo. Check with a select first.
Found by the where, versus actually made different.
What does update students set grade = 12; do?
An update reports 'Rows matched: 5 Changed: 2'. What happened?
Which correctly changes two columns of one row?