Intermediate
20 min read
Insert
By the end of this lesson, you'll be able to:
- Insert a single record and a list of records
- Read the auto-populated Id after an insert succeeds
- Handle a validation failure using try/catch
Prerequisites: "What Is DML?"
Inserting a single record
Account acc = new Account(Name = 'Riverbend Farms');
insert acc;
System.debug(acc.Id); // now populated — e.g. 001XX000003DHP0YAO
Account acc = new Account(Name = 'Riverbend Farms');— beforeinsert,acc.Idisnull.insert acc;— assigns theIdautomatically the instant the insert succeeds.- (blank line)
System.debug(acc.Id);— now populated — this is exactly the 18-character Id format from Module 18.
Inserting a List at once
List<Account> newAccounts = new List<Account>{
new Account(Name = 'Riverbend Farms'),
new Account(Name = 'Northwind Traders')
};
insert newAccounts;
for (Account acc : newAccounts) {
System.debug(acc.Id);
}
List<Account> newAccounts = new List<Account>{— a list of records to create.new Account(Name = 'Riverbend Farms'),— the first, not yet saved.new Account(Name = 'Northwind Traders')— the second, not yet saved.};— closes the list literal.- (blank line)
insert newAccounts;— a single DML statement covering every record in the list — this is exactly the bulkification instinct from Module 7's "Loops and Governor Limits" lesson.- (blank line)
for (Account acc : newAccounts) {— loops over the now-saved records.System.debug(acc.Id);— each one now has a real, permanent Id.}— closes the loop.
Handling a validation failure
try {
Account acc = new Account(); // no Name — Name is required on Account
insert acc;
} catch (DmlException e) {
System.debug('Insert failed: ' + e.getMessage());
}
try {— wraps the risky insert.Account acc = new Account();— noName—Nameis required onAccount.insert acc;— a record that violates a required-field or validation rule throws aDmlExceptionhere.} catch (DmlException e) {— exactly Module 13'stry/catchpattern, now catching a database-level failure instead of a runtime language error.System.debug('Insert failed: ' + e.getMessage());— handles it instead of crashing.}— closes thecatch.
Exercise
Build a List<Account> with two new Accounts (Name only), insert them, and debug each one's Id after the insert.
Show hint
insert the whole List at once.
Insert 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
insert creates one or more brand-new records — a single sObject or a whole List at once — and Salesforce assigns each one a real, permanent Id the moment it succeeds.