SOSL (Salesforce Object Search Language)
1. What is SOSL?
SOSL (Salesforce Object Search Language) is used to search multiple objects at once in Salesforce.
It’s helpful when:
• You’re looking for a keyword (like a name or email),
• You don’t know which object has the data, • You want to search across objects quickly.
SOSL Syntax:
FIND ‘searchText’
IN ALL FIELDS
RETURNING Object1(Field1), Object2(Field2)
Components:
• FIND ‘searchText’: The term or keyword you are searching for.
• IN ALL FIELDS: Specifies that the search should look across all searchable fields.
• RETURNING Object(…): Lists the objects and fields you want to retrieve from the search
Using SOSL in Developer Console
1. Log in to your Salesforce org.
2. Open the Developer Console (Gear icon → Developer Console).
3. Click Debug > Open Execute Anonymous Window.
4. Paste the SOSL code. 5. Click Execute.
6. Open the log to see results under Debug Only.
Example 1: Search Email in Lead & Contact
List<List<SObject>> results = [FIND ‘john.doe@example.com’
IN EMAIL FIELDS
RETURNING Lead(Email), Contact(Email)];
Explanation:
This searches for the email john.doe@example.com in both Lead and Contact objects.
Expected Output (in Debug Log):
Lead: (john.doe@example.com)
Contact: (john.doe@example.com)
Example 2: Search Company Name in Account and Opportunity
List<List<SObject>> results = [FIND ‘Acme’
RETURNING Account(Name), Opportunity(Name)];
System.debug(results);
Searches for the keyword “Acme” in both Account and Opportunity names.
Expected Output:
Account: (Acme Corp)
Opportunity: (New Deal with Acme)
Example 3: Search "urgent" in Tasks and Custom Support Cases
List<List<SObject>> results = [FIND ‘urgent’
RETURNING Task(Subject), Case_Submission__c(Subject__c)];
System.debug(results);
Searches the word “urgent” in Tasks and custom object Case_Submission__c.
Expected Output:
Task Subject: Urgent follow-up
Case_Submission__c Subject__c: Urgent system error
Example 5: Search for Users with "Manager" in Title
List<List<SObject>> results = [FIND ‘Manager’
RETURNING User(Name WHERE Title LIKE ‘%Manager%’)];
System.debug(results);
Explanation:
Finds Users whose job title includes the word “Manager”.
Expected Output:
User: (Name: Alice Manager, Title: Sales Manager)
User: (Name: Bob Leader, Title: Project Manager)