SOSL – Salesforce Object Search Language

SOSL – Salesforce Object Search Language

Unlike SOQL, which can only query one object at a time and multiple objects only if they are related to each other, SOSL enables you to
search text, email, and phone fields for multiple objects simultaneously.

Use SOSL with the search() call to find records for one or
more objects. The
search() call searches most text fields on
an object.

Sample SOSL:

FIND {test}
IN Name FIELDS
RETURNING
Account( Id, Name ), Contact( Id, Name )

Sample Apex Code:

String searchQuery = ‘FIND {test} IN Name FIELDS RETURNING Account( Id, Name ), Contact( Id, Name )’;
List < List < sObject > > searchResult = search.query( searchQuery );
List < Account > listAccount = ( List < Account > )searchResult.get( 0 );
List < Contact > listContact = ( List < Contact > )searchResult.get( 1 );
for ( Account acc : listAccount ) {
    
    System.debug( acc );
    
}
for ( Contact con : listContact ) {
    
    System.debug( con );
    
}

Leave a Reply