Sub topic 1
Searching Across Objects with SOSL
Prerequisites
Assume you know Salesforce objects, fields, and records, and you can read basic SOQL and Apex. SOSL is Salesforce Object Search Language. It searches text across multiple objects in one operation. Salesforce searches an indexed copy of the data, rather than scanning every record field by field.
A SOSL query has a FIND clause for the search expression and usually a RETURNING clause for the objects and fields to return.
List<List<SObject>> results = [
FIND 'Acme*' IN NAME FIELDS
RETURNING Account(Id, Name), Contact(Id, Name)
];The result contains one list for each object in RETURNING, in the same order. Here, results[0] contains Accounts and results[1] contains Contacts.
SOSL or SOQL: choosing the right tool
Use SOQL when you know the object and need structured filtering, joins through relationships, or exact field conditions. Use SOSL when a user enters text and the search may match several objects or text fields.
| Requirement | Better choice |
|---|---|
| Find Accounts where `Industry = 'Technology'` | SOQL |
| Find “Acme” in Accounts and Contacts | SOSL |
SOSL does not replace SOQL. A common pattern is to use SOSL to discover records, then use SOQL for detailed retrieval.
Writing a FIND clause
The basic form is:
FIND 'search expression' IN search groupThe expression can include wildcards. * matches zero or more characters, so Acme* can match “Acme” and “Acme Corporation.” Use logical operators such as AND, OR, and AND NOT to combine terms. Exact phrases and some SOSL interfaces use braces, such as FIND {"Acme Corp" OR Globex*}.
Choosing where to search with search groups
The search group controls which indexed fields SOSL examines:
ALL FIELDSsearches all searchable fields.NAME FIELDSsearches name fields.EMAIL FIELDSsearches email fields.PHONE FIELDSsearches phone fields.SIDEBAR FIELDSsearches fields used by Salesforce search features.
Choose the narrowest group that matches the requirement. This makes the intent clearer and avoids unrelated matches.
Exercise
Which language should you use to find “Acme” across Account and Contact name fields?
Show answer
Use SOSL with FIND 'Acme' IN NAME FIELDS and a RETURNING clause for Account and Contact.