You need to sign in to do that
Don't have an account?

Does a For Loop select records at random if an index is not specified?
Hello - Below is a soql query I'm using to retrieve leads and a For Loop to update the lead. I'm finding that the For Loop selects a record at random. Sometimes the For Loop updates the oldest lead and sometimes the newest lead. Is there any logic to the record returned by the For Loop if no index is specified?
existingLead = [SELECT Id, street, LastName, PostalCode, LastNameStreetAndZipCode__c, Core_Number_Text__c, Status, Home_Phone__c, CreatedDate, Core_Number__c, Policy_Core_Number__c, Lead_Type__c FROM LEAD WHERE ( Policy_Core_Number__c IN :coreNumberTextSet OR Core_Number__c IN :coreNumberTextSet OR ( LastNameStreetAndZipCode__c IN :lastNameStreetZipSet AND Core_Number__c NOT IN :coreNumberTextSet) OR (LastNameStreetAndZipCode__c IN :setOfPoBoxes AND Core_Number__c NOT IN :coreNumberTextSet)) AND Household__c != null AND Duplicate__c != True AND IsDeleted = False ORDER BY CreatedDate ASC LIMIT 20000];
if(existingLead.size() > 0){ for(Lead leadsToAddToMap : existingLead) { mapOfCoreNumbers.put(leadsToAddToMap.Core_Number__c, leadsToAddToMap.Core_Number__c); mapOfCreatedDate.put(leadsToAddToMap.LastNameStreetAndZipCode__c, leadsToAddToMap.CreatedDate); } }
Are you sure your soql return those records? Can you system.debug on your SOQL results making sure you getting those records?
All Answers
What is your definition of old Leads vs New Leads?
I do see you SOQL has ORDER BY CreatedDate ASC, the list existingLead must contain Leads in that sequence and run the for loop accordingly. Since you haven't provided the full update version so not sure if there anything happening. I also see you have two maps so you may be manipulating something based on that otherwise I don't see any issues with the sequence.
Test 1: Soql returned 2 records (same customer):
Jones, created date 1/1/2020
Jones, created date 5/15/2020
The For Loop returned the lead from 1/1/2020
Test 2: Soql returned 2 records (same customer):
Phelps, created date 6/1/2020
Phelps, created date 8/15/2021
The For Loop returned the lead from 8/15/2021
Are you sure your soql return those records? Can you system.debug on your SOQL results making sure you getting those records?
Can you re check with some other simple query let say on Account and confirm if your observations is same.