ApexSensei

Drills Debugging

Fix a query inside a loop

Too many SOQL queries: 101 is the classic production failure.

Your task

Fix the handler so it runs at most one query however many Contacts are inserted, and still stamps each Contact with its Account's name.

public class AS_A9DF0520ABDF_AccountStamp {
    public static void beforeInsert(List<Contact> contacts) {
        for (Contact contact : contacts) {
            if (contact.AccountId == null) {
                continue;
            }
            Account account = [
                SELECT Name
                FROM Account
                WHERE Id = :contact.AccountId
            ];
            contact.Description = 'Works at ' + account.Name;
        }
    }
}

Requirements

  1. stampsTheAccountName should pass
  2. leavesAContactWithoutAnAccountAlone should pass
  3. usesOneQueryForTwoContacts should pass
  4. handlesTwoHundredContacts should pass
  5. handlesAMixOfWithAndWithoutAccounts should pass

Sign in to open this drill