+ Start a Discussion

SOQL help.

Hi, For efficiency I need to gather all with a single SOQL; however can someone point me how to achive a lookup type scenario with a single SOQL; Some snippet I have:


for(Contact cnt_old:oldContacts) { List cnt = [select email from Contact where id =: cnt_old.masterrecordid];


I need to use masterrecordid due to delete happens from a merge action and get other cols of the winning records.


After getting winning records/cols I then need to relate to oldContacts....both queries are on same contact obj

So, now I have select within For loop, which I need to avoid, thanks!

Best Answer chosen by Admin (Salesforce Developers) 
Jake GmerekJake Gmerek

I'm not sure if this is exactly what you want, but it should give you an idea on how to get started:


List <id> contactIds = new List<Id>();

for(Contact cnt_old:oldContacts){

List<contacts> cnt = new List<Contact>([select email from Contact where id IN: contactIds]);

Map<ID, List<Contact>> lookup = new map<ID, List<contact>();

for(Contact cnt_old:oldContacts){
  if (lookup.get(cnt_old.id) == NULL){
     lookup.put(cnt_old.id, new List<Contact>());
  for (contact c: cnt){
    if (cnt.id == cnt_old.masterrecordid){