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;
  1. Account acc = [SELECT Id, Name, Industry FROM Account WHERE Name = 'Riverbend Farms' LIMIT 1]; — queries an existing record, including its Id, populated exactly like Module 18's relationship lessons.
  2. acc.Industry = 'Agriculture'; — changes a field in memory.
  3. (blank line)
  4. update acc; — uses the record's existing Id to 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
  1. Account acc = new Account(Name = 'Test'); — never inserted — Id is null.
  2. // update acc; — commented out because this line would throw — update has no record to find without an Id, the key distinction from insert, 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;
  1. List<Account> techAccounts = [SELECT Id, Industry FROM Account WHERE Industry = 'Technology']; — queries every matching record at once.
  2. (blank line)
  3. for (Account acc : techAccounts) { — loops over the records, making in-memory changes only.
  4. acc.Industry = 'Technology - Legacy'; — changes a field, not yet saved.
  5. } — closes the loop.
  6. (blank line)
  7. update techAccounts; — a single update statement 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 a DML statement 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

1. Why does update require the record to already have an Id?

Log in to submit the quiz and save your score.

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.