Searching Multiple Objects
By the end of this lesson, you'll be able to:
- Search and return results from more than one object in a single SOSL statement
- Limit which fields are searched using IN NAME FIELDS or IN specific field groups
- Process each object's results separately after the search runs
Prerequisites: "Your First SOSL Search"
Searching several objects at once
List<List<sObject>> searchResults = [
FIND 'Riverbend' IN ALL FIELDS
RETURNING Account(Id, Name), Contact(Id, LastName, Email), Lead(Id, Company)
];
List<Account> accounts = searchResults[0];
List<Contact> contacts = searchResults[1];
List<Lead> leads = searchResults[2];
System.debug('Found ' + accounts.size() + ' accounts, ' + contacts.size() + ' contacts, ' + leads.size() + ' leads.');
This is the direct payoff from this module's first lesson — one search, three object types, a single round trip instead of three separate SOQL queries.
Narrowing the search with IN NAME FIELDS
List<List<sObject>> searchResults = [
FIND 'Riverbend' IN NAME FIELDS
RETURNING Account(Id, Name)
];
IN ALL FIELDS searches every searchable text field on each object; IN NAME FIELDS narrows the search specifically to name-type fields (like Account.Name or Contact.LastName) — useful when you know you're searching for a name specifically, not scanning notes or descriptions too.
A real business example: Global Support Search
String searchTerm = 'connectivity issue';
List<List<sObject>> searchResults = [
FIND :searchTerm IN ALL FIELDS
RETURNING Case(Id, Subject, Status), Knowledge__kav(Id, Title)
];
A support agent's global search box searching both open Case records and a knowledge base article object at once is a textbook SOSL scenario — one search box, multiple object types, exactly the shape this module exists for. (Note the :searchTerm bind variable — Module 20's bind variable syntax works in SOSL too.)
Exercise
Write a SOSL search for 'Dlamini' across both Contact (Id, LastName) and Lead (Id, LastName), then debug each list's size.
Show hint
RETURNING Contact(Id, LastName), Lead(Id, LastName)
Searching Multiple Objects Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
A single SOSL search can span several objects at once — genuinely useful whenever a search term could plausibly belong to more than one kind of record.