In an Apex class method, I want to add several Accounts to a List. After a successful execution of the insert, can I access Ids?


List<Account> accounts = new List<Account>();
Account newAccount = new Account();
newAccount.Name = 'Acme, Inc.';
insert accounts;

for (Account thisAccount: accounts) {

Will thisAccount.Id have a value or must I execute a new SOQL statement?

Per this documentation under Inserting Related Records, it looks like it should contain the newly-assigned Salesforce Id.

  • As a first step running the code in anonymous would have given you the answer. May save you some time next time waiting for an answer – Eric Oct 10 '20 at 6:58

Yes. Every insert DML operation that you successfully perform populates the Id field of the inserted sObject.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.