I have a list of id's i want to populate their name.

This list contains account ids, contact ids, etc. Not only one sobjectType id.

I created a map that the key is the sobjectType, and the value is a list of all the id's of that type.

now i want to go over that list,generate a query for every sObject seperately, and populate the id's.

i have no idea how to do that without having the queries in a loop.

Set<Id> idsToPopulate = new Set<Id>();

    Map<String, Set<Id>> idTypeToIdsMap = new Map<String, Set<Id>>();

    for(field_audit_entry__c entry_i : allEntries) {
    for(Id id_i : idsToPopulate) {
        String idType = String.valueOf(id_i.getSobjectType());
            idTypeToIdsMap.put(idType, new Set<Id>());

This is what i have so far, please advise

  • Well I belive you have to do SOQL in a for loop, there are multiple objects and thus multiple querries Mar 27, 2019 at 9:47

1 Answer 1


As far as I know, you will have to do the query in for loop for this requirement, but you should make sure that your map does not have many sObjectTypes. From your example, if you have Account and Contact, then it will result in two SOQL statements.

Further to your code, below code should suffice your needs which will give you the Map<string, Map<Id, sObject>> i.e. it will contain the records sObjectType wise. For example, this map will contain '(Account'=>('Id'=> Account))

//to construct the dynamic query
string queryString ='';
//to filter by the Ids as apex doesn't work in dynamic SOQL
Set<Id> setIds = new Set<Id>();
//Map to store results i.e. map of object type with map of results i.e. Id with sObject
Map<string, Map<Id,sObject>> mapSObjectRecords = new Map<string,Map<Id,sObject>>(); 
//Map to store individual results
Map<Id,sObject> mapRecords = new Map<Id,sObject>();
for(string objectName : idTypeToIdsMap.keyset()){
    setIds = idTypeToIdsMap.get(objectName);
    queryString = 'SELECT ID, NAME FROM ' + objectName + ' where Id IN :setIds';
    mapRecords = new Map<Id,sObject>(); //will need to check if we can use the dynamic query to get the results in map without having to use for loop
    for(sObject record : Database.query(queryString)){
        mapRecords.put(record.Id, record);
    mapSObjectRecords.put(objectName, mapRecords);

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .