function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Saad Ahmad 49Saad Ahmad 49 

What would be the SOQL statement to return all the account ID's for various contacts IDs?

Trying to get all account ID's based on a list of contact ID's I have. Any example SOQL statements would be great. 

Thanks! 
CharuDuttCharuDutt
Hii Saad 
Try Below Code
Query : [select id,Name,AccountId,Account.Name from Contact Where AccountId !=Null]

===================================================================================================================

list<Contact> lstCon = [select id,Name,AccountId,Account.Name from Contact Where AccountId !=Null];
for (Contact Con:lstCon){
    System.Debug('Contact AccountId And AccountName ==> '+ Con.AccountId+'  '+ Con.Account.Name );
}
Please Mark It As Best Answer If it Helps
Thank You!
Suraj Tripathi 47Suraj Tripathi 47
public class fetchAccountIdsandRelatedContacts 
{
    public static void mapMethod()
    {
        Map<Id,List<Contact>> accountToContactMap=new Map<id,List<Contact>>();        
        List<Contact> contactlist=new List<Contact>([SELECT Id,Name,AccountId,email FROM CONTACT WHERE AccountId!=null limit 100]);
        for(Contact con:contactlist)
        {                        
            if(!accountToContactMap.containsKey(con.AccountId))
            {                
                List<Contact> conls=new List<Contact>();
                conls.add(con);
                accountToContactMap.put(con.AccountId,conls);
            }
            else
            {                                
                List<contact> conls=accountToContactMap.get(con.AccountId);
                conls.add(con);
                accountToContactMap.put(con.AccountId,conls);                       
            }                                     
        }
         system.debug('Map of Account: '+accountToContactMap);   
    }   
}
ravi soniravi soni
hi Saad,
you need to try below code if you have list of contact ids. below class will return list of Account ids that contains in contact ids that you passed by parameters.
public class fetchAccountIdsandRelatedContacts 
{
    public static set<string> fetchAccountRecords(list<string> conIds){
		set<string> accountIds = new set<string>();

		for(Contact con : [SELECT Id,name,AccountId FROM Contact WHERE Id In :conIds ]){
			if(con.AccountId != null){
			accountIds.add(con.AccountId);
			}
			
		}
		system.debug('accountIds===>' + accountIds);
		
       return accountIds;
    }   
}

don't forget to mark it as best answer if it help you.
Thank you
ravi soniravi soni
hy Saad Ahmad 49,
did you try any code if not then please try it and mark it as best answer.
Thank you
Saad Ahmad 49Saad Ahmad 49
@veer where am I referencing all of my 300 contact ID's in your code? Also, confused, is this being ran through the developer console?