Search Across Warehouses (SOSL)
By the end of this lesson, you'll be able to:
- Search Product__c by name or SKU using SOSL
- Combine a SOSL search with a follow-up query for stock details
- Explain why SOSL alone isn't always the full answer
Prerequisites: "Process Stock Adjustments (DML)"
Searching products by name or SKU
public List<Product__c> searchProducts(String searchTerm) {
List<List<sObject>> searchResults = [
FIND :searchTerm IN ALL FIELDS
RETURNING Product__c(Id, Name__c, SKU__c)
];
return (List<Product__c>) searchResults[0];
}
This is Module 21's SOSL pattern from Module 22's library search, applied to Product__c instead of Book__c — one search matching either the product name or its SKU.
Combining search with a stock lookup
public List<Warehouse_Stock__c> searchProductsWithStock(String searchTerm) {
List<Product__c> matchingProducts = searchProducts(searchTerm);
Set<Id> productIds = new Set<Id>();
for (Product__c product : matchingProducts) {
productIds.add(product.Id);
}
return [
SELECT Id, Product__r.Name__c, Warehouse_Name__c, Quantity_On_Hand__c
FROM Warehouse_Stock__c
WHERE Product__c IN :productIds
];
}
The SOSL search finds matching products; a Set<Id> (Module 16) collects their Ids; a single follow-up SOQL query with IN :productIds (Module 20) pulls every stock record for all of them at once — no query inside a loop, even though this method effectively answers "search and show stock" in one call.
Why SOSL alone isn't always the full answer
SOSL is excellent at finding matching products, but Warehouse_Stock__c records don't directly contain searchable text like a product name — they only reference a product by Id. Getting from "found matching products" to "here's their stock breakdown" genuinely needs a second, related query, exactly like this lesson's two-step method. Recognizing when a single tool (SOSL) needs a follow-up step is itself part of designing this kind of feature well.
Exercise
Call searchProductsWithStock for the term "Widget" and debug how many stock records were found.
Show hint
inventory.searchProductsWithStock('Widget')
Search Across Warehouses (SOSL) 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
This lesson lets a manager search for a product by name or SKU, then pulls its full stock breakdown across every warehouse — combining SOSL with the relationship queries from earlier in this module.