Above SOSL will search for the term “Salesforce” in both the Account and Contact objects, returning mentioned in SOSL fields from each. It is an easy way to perform a broad search without writing multiple queries.
Making It All Together
Both SOQL and SOSL are essential for accessing and managing our Salesforce data. Below is a simple scenario that illustrates how we use both query languages in our code as per the business requirements.
Imagine we are tasked or required with creating a feature for a Salesforce app that needs to display details about accounts and let users search for records quickly.
Example: Combining SOQL and SOSL
public class SalesforceDataQuery {
// Below method will retrieve all active accounts sorted by name
public static List<Account> getActiveAccounts() {
return [SELECT Id, Name FROM Account WHERE IsActive = true ORDER BY Name ASC];
}
// Below method uses SOSL to search for a keyword across multiple objects
public static List<List<SObject>> searchKeyword(String searchTerm) {
return [FIND :searchTerm IN ALL FIELDS RETURNING Account(Id, Name), Contact(Id, FirstName, LastName)];
}
public static void demoQueryFunctions() {
// Retrieve and log active accounts
List<Account> activeAccounts = getActiveAccounts();
System.debug('Active Accounts: ' + activeAccounts);
// Search for a keyword and log results
List<List<SObject>> searchResults = searchKeyword('Salesforce');
System.debug('Search Results: ' + searchResults);
}
}