Why does SOSL return a List of a List of sObjects in Apex?

When I use SOSL in Apex (search.query();) the return type is List<List<sObject>>, but I’ve never run across a case in which there is more than one list returned.

For example, this:

string q= 'FIND {"John Doe"} Returning Contact(Id, Email, Name, Account.Name)';
List<List<sObject>> ListOfListOfSObjects = search.query(q);

system.debug('Number of Lists: '+ListOfListOfSObjects.size());
for(Integer i=0; i<ListOfListOfSObjects.size(); i++)
    system.debug('List '+(i+1)+' size: '+ListOfListOfSObjects[i].size());


16:18:42.137 (137179000)|USER_DEBUG|[4]|DEBUG|Number of Lists: 1
16:18:42.137 (137575000)|USER_DEBUG|[7]|DEBUG|List 1 size: 2

When would SOSL return more than one List of sObjects? Did I miss something in the documentation?


SOSL has the ability to search across multiple objects in one query. So if you do something like the following it will return results from Accounts, Contacts, Opportunities, and Leads.

List<List<SObject>> searchList = [FIND 'map*' IN ALL FIELDS RETURNING Account (Id, Name), Contact, Opportunity, Lead];
Account [] accounts = ((List<Account>)searchList[0]);
Contact [] contacts = ((List<Contact>)searchList[1]);
Opportunity [] opportunities = ((List<Opportunity>)searchList[2]);
Lead [] leads = ((List<Lead>)searchList[3]);

Source : Link , Question Author : Matt K , Answer Author : Greg Grinberg

Leave a Comment