Cheatsheet

SOQL query inside for loop

Estimated reading: 1 minute 27 views

Bad-Good

				
					for (Account acc : accountList) {
    // SOQL inside the loop - BAD PRACTICE
    Contact contact = [SELECT Id, Name FROM Contact WHERE AccountId = :acc.Id LIMIT 1];
    System.debug('Contact: ' + contact);
}

				
			
				
					// Step 1: Collect all account IDs in a set
Set<Id> accountIds = new Set<Id>();
for (Account acc : accountList) {
    accountIds.add(acc.Id);
}

// Step 2: Query all contacts related to those accounts in one SOQL query
Map<Id, Contact> accountToContactMap = new Map<Id, Contact>(
    [SELECT Id, Name, AccountId FROM Contact WHERE AccountId IN :accountIds]
);

// Step 3: Loop through accounts and match contacts using the map
for (Account acc : accountList) {
    if (accountToContactMap.containsKey(acc.Id)) {
        Contact relatedContact = accountToContactMap.get(acc.Id);
        System.debug('Related Contact: ' + relatedContact.Name + ' for Account: ' + acc.Name);
    } else {
        System.debug('No contact found for Account: ' + acc.Name);
    }
}

				
			
Share this Doc

SOQL query inside for loop

Or copy link

CONTENTS