Intermediate
20 min read
Update
By the end of this lesson, you'll be able to:
- Update an existing record's fields and save the change with update
- Explain why a record must already have an Id before update works
- Update a List of records queried from the database
Prerequisites: "Insert"
Updating a single record
Account acc = [SELECT Id, Name, Industry FROM Account WHERE Name = 'Riverbend Farms' LIMIT 1];
acc.Industry = 'Agriculture';
update acc;
Account acc = [SELECT Id, Name, Industry FROM Account WHERE Name = 'Riverbend Farms' LIMIT 1];— queries an existing record, including itsId, populated exactly like Module 18's relationship lessons.acc.Industry = 'Agriculture';— changes a field in memory.- (blank line)
update acc;— uses the record's existingIdto find and modify the matching database row — this doesn't create a new record, it changes the existing one in place.
Why update needs an existing Id
Account acc = new Account(Name = 'Test'); // never inserted — Id is null
// update acc; // throws: Id not specified in an update call
Account acc = new Account(Name = 'Test');— never inserted —Idisnull.// update acc;— commented out because this line would throw —updatehas no record to find without anId, the key distinction frominsert, which creates a brand-new row and doesn't need one.
Updating a List of queried records
List<Account> techAccounts = [SELECT Id, Industry FROM Account WHERE Industry = 'Technology'];
for (Account acc : techAccounts) {
acc.Industry = 'Technology - Legacy';
}
update techAccounts;
List<Account> techAccounts = [SELECT Id, Industry FROM Account WHERE Industry = 'Technology'];— queries every matching record at once.- (blank line)
for (Account acc : techAccounts) {— loops over the records, making in-memory changes only.acc.Industry = 'Technology - Legacy';— changes a field, not yet saved.}— closes the loop.- (blank line)
update techAccounts;— a singleupdatestatement outside the loop saves all of them at once — this is the exact bulkification pattern from Module 7's "Loops and Governor Limits" lesson, never aDMLstatement inside the loop.
Exercise
Given List<Account> accounts already queried with Id and Industry, loop over them setting Industry to 'Reviewed', then update the whole list once.
Show hint
Set the field inside the loop; call update outside the loop.
APEX
Update Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
update saves changes to a record that already exists in the database — identified by its Id, which is why a record typically needs to be queried or just-inserted before it can be updated.