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
Before insert, acc.Id is null — it's assigned automatically by Salesforce the instant the insert succeeds. 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);
}
Inserting a List performs a single DML statement covering every record in it — this is exactly the bulkification instinct from Module 7's "Loops and Governor Limits" lesson, and it's the standard way to insert multiple records safely.
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());
}
A record that violates a required-field or validation rule throws a DmlException when insert runs — exactly Module 13's try/catch pattern, now catching a database-level failure instead of a runtime language error.
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.