ApexSensei

Drills › Change records (DML)

Insert an Account with Contacts

Change records (DML) · Intermediate · 18 min · Runs in your Salesforce Developer org · Apex Path

Scenario. A new customer signs up with three team members. Their Account and Contacts must be saved together and linked.

Insert a parent Account, then its three Contacts in one list with AccountId set, and prove the link with a query.

What you will learn

To link a child record to its parent, set the child's lookup field to the parent's Id. The parent gets an Id only when you insert it, so insert the parent first. Then insert all the children in one list.

insert parent;
for (Contact person : contacts) {
    person.AccountId = parent.Id;
}
insert contacts;

Gotcha. If you read parent.Id before insert parent, it is null, and the Contacts save with no Account.

The task

Insert one tagged Account and three Contacts that belong to it, using exactly two DML statements.

Examples:

  • insert the Account, then all three Contacts in one list → DML used: 2
  • a query from the Account down to its Contacts finds all three → Contacts linked: 3
  • no tagged Contact is left without an Account → Orphan contacts: 0

Requirements:

  1. Insert parent first, so it has an Id.
  2. Build one Contact per name in lastNames, with LastName = tag + '-' + name and AccountId = parent.Id. Add them all to contacts, then insert that list once.
  3. Query the Account with a child subquery, (SELECT Id FROM Contacts), and set linkedCount from its size.
  4. Count tagged Contacts whose AccountId is null into orphanCount. Print Contacts linked:, Orphan contacts: and DML used:.

Starter code

String tag = 'AS-INSERTC-' + UserInfo.getUserId() + '-' +
    String.valueOf(Datetime.now().getTime());
String tagPattern = tag + '-%';
List<String> lastNames = new List<String>{ 'Ito', 'Park', 'Diaz' };
Integer dmlBefore = Limits.getDmlStatements();
Account parent = new Account(Name = tag);
List<Contact> contacts = new List<Contact>();

Integer linkedCount = -1;
Integer orphanCount = -1;
System.debug('Contacts linked: ' + linkedCount);
System.debug('Orphan contacts: ' + orphanCount);
System.debug('DML used: ' + (Limits.getDmlStatements() - dmlBefore));

When it passes

One insert saves the Account, one more saves all three Contacts, and the query shows every Contact under that Account.

Try this drill free

You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.

‹ Savepoint and rollback