insert creates a record. update changes one that is already there, and it carries one
requirement that insert did not have: the record must know the Id of the row it belongs
to.
You cannot update something you do not have. Query for the record, assign the new value
to the field, and save it:
List<Account> rows = [SELECT Id, Name, Rating FROM Account WHERE Name = 'Nordic Petroleum'];
for (Account account : rows) {
account.Rating = 'Cold';
update account;
}
Three steps, in this order: query the record, change the field on it, call update on
that same record object.
Building a fresh object and calling update on it fails, because the database has no way
to know which row you mean:
Update failed. First exception on row 0; first error: MISSING_ARGUMENT, Id not specified in an update call: []
A query hands you a record that already carries its Id, which is why the query always
comes first.
An update writes the fields you actually changed, not every field of the record. Query
an Account without its Phone, change only the Rating, and the Phone is left alone. That
is what makes a partial update safe: you do not have to read a whole record to change
one field on it.
This is the trap that sets updating apart from inserting. Assigning an empty String or a
null to a field and saving it does not raise an error, and it does not leave the old
value in place. The field is cleared:
account.Rating = ''; update account; // the Rating is now null
So guard a value before you write it. If the new value is blank, do not update the
record at all.
A query that matches nothing returns an empty list, and reading rows[0] on it throws
System.ListException: List index out of bounds: 0. Check rows.isEmpty() before you
read the list, and remember that update on a list saves every record in the list in a
single call.
The first mistake is updating a record that has no Id. The second is writing a blank
value and silently clearing a field that used to hold real data. The third is reading
the first element of a query result that might be empty.
Update is how a record changes over time, and it is the foundation of the next lesson.
A rule that says "when this happens, set that field" is an update, and every such rule
needs the same two guards: find the record first, and never write a blank value by
accident.