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;

update uses the record's existing Id (populated by the query, exactly like Module 18's relationship lessons) to find and modify the matching database row — changing Industry here 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

update has no record to find without an Id — this is the key distinction from insert, which creates a brand-new row and doesn't need one. Attempting to update a record that was never inserted (or queried) throws a DmlException.

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;

This is the exact bulkification pattern from Module 7's "Loops and Governor Limits" lesson: loop over the records making in-memory changes, then a single update statement outside the loop saves all of them at once — 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.