SOQL
|
SOSL
|
SOQL is used if we know in which object the data is present. | SOSL is used if we don’t know in which object the data is present. |
In SOQL we can query data from the single object and as well as multiple objects. In case of multiple objects, the objects should have some relationship between them. | In SOSL we can search data from multiple objects even if there is no relationship among the objects. |
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.
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 );
}