2

Gentlemen, simple question. Does Apex wait for the DML operation of inserting accounts to complete before moving onto the next line (SOQL statement)?

insert parentAcctList;

List<Id> acctIdList = [SELECT id
                       FROM Account];

for(Id acctId : acctIdList) {
     Contact cont = new Contact(lastName = 'Lee', 
                                firstName = 'Robert', 
                                title = 'General', 
                                AccountId = acctId);
     insert cont; 
1
  • 1
    Yes. Apex executes line by line. Commented Jul 22, 2016 at 11:31

1 Answer 1

4

Yes.

The code as you've provided is not considered 'bulkified' because it will execute an insert for each acctId.

You'd probably want to add the Contacts to a list, then insert that list outside of your for loop.

i.e.

List<Contact> contactsToInsert = new Map<Contact>();

for(Id acctId : acctIdList) {
    contactsToInsert.add(new Contact(lastName = 'Lee', firstName = 'Robert'));
}

insert contactsToInsert;
1
  • Thank you for the answer! Yes, I am aware its not bulkified, just some code to frame the question about the account DML insertion. Commented Jul 22, 2016 at 0:56

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .