Query Low-Stock Items
By the end of this lesson, you'll be able to:
- Query stock records below their reorder threshold
- Traverse a parent relationship to include the product's name in the results
- Sort low-stock results by how far below threshold they are
Prerequisites: "Track Inventory Levels"
Filtering to stock below threshold
public List<Warehouse_Stock__c> getLowStockItems() {
return [
SELECT Id, Product__c, Warehouse_Name__c, Quantity_On_Hand__c, Reorder_Threshold__c
FROM Warehouse_Stock__c
WHERE Quantity_On_Hand__c < Reorder_Threshold__c
];
}
Comparing two fields on the same object directly in WHERE — Quantity_On_Hand__c < Reorder_Threshold__c — is exactly Module 20's comparison-operator filtering, now comparing one field against another instead of against a fixed value.
Including the product name via a parent relationship
public List<Warehouse_Stock__c> getLowStockItemsWithProductName() {
return [
SELECT Id, Product__r.Name__c, Warehouse_Name__c, Quantity_On_Hand__c
FROM Warehouse_Stock__c
WHERE Quantity_On_Hand__c < Reorder_Threshold__c
];
}
Product__r.Name__c reaches through the relationship to the parent Product__c's name — this is Module 18's and Module 20's parent-relationship traversal directly applied. Note Product__r (with __r, the relationship suffix), not Product__c (the raw lookup field itself) — a naming detail worth being deliberate about.
Sorting by how urgent the shortage is
public List<Warehouse_Stock__c> getLowStockItemsSortedByUrgency() {
return [
SELECT Id, Product__r.Name__c, Warehouse_Name__c, Quantity_On_Hand__c, Reorder_Threshold__c
FROM Warehouse_Stock__c
WHERE Quantity_On_Hand__c < Reorder_Threshold__c
ORDER BY Quantity_On_Hand__c ASC
];
}
Sorting ascending by Quantity_On_Hand__c puts the most critically low items first — a manager scanning this list top-to-bottom sees the most urgent reorders before less pressing ones.
Exercise
Write a method getOutOfStockItems() returning Warehouse_Stock__c records where Quantity_On_Hand__c equals exactly 0.
Show hint
WHERE Quantity_On_Hand__c = 0
Query Low-Stock Items 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 warehouse manager's most common question is "what needs reordering?" — this lesson answers it directly with a filtered, sorted query.