ApexSensei

Drills SOQL queries

Match an Account list

IN :collection matches any value in a Set or List.

Your task

Collect the Account Ids from a list of Contacts, then load those Accounts with one IN query.

String tag = 'AS-Q308-' + UserInfo.getUserId() + '-' +
    String.valueOf(Datetime.now().getTime());
List<Account> accounts = new List<Account>{
    new Account(Name = tag + '-A'),
    new Account(Name = tag + '-B'),
    new Account(Name = tag + '-C')
};
insert accounts;
List<Contact> contacts = new List<Contact>{
    new Contact(LastName = tag + '-1', AccountId = accounts[0].Id),
    new Contact(LastName = tag + '-2', AccountId = accounts[2].Id),
    new Contact(LastName = tag + '-3', AccountId = accounts[2].Id),
    new Contact(LastName = tag + '-4')
};

Set<Id> accountIds = new Set<Id>();
List<Account> matches = new List<Account>();
System.debug('Unique Account Ids: ' + accountIds.size());
System.debug('Accounts found: ' + matches.size());
System.debug('Account B left out: false');

Requirements

  1. .AccountId should be present
  2. Id IN :accountIds should be present
  3. Unique Account Ids: 2 should be printed
  4. Accounts found: 2 should be printed
  5. Account B left out: true should be printed
  6. Queries used: 1 should be printed

Sign in to open this drill