0

Covered Product is an object and Installed product is a lookup field on Covered product and Status is a picklist field on Installed product.

When I am trying to run the below code in Execute Anonymous window then I am getting error : Line: 4, Column: 1 System.SObjectException: SObject row was retrieved via SOQL without querying the requested field: Service_Contract_Products__c.Installed_Product__r. But when I am running the same code inside a class I am not getting the error.

Can someone please provide the solution how to check the status of Installed product in Covered Product object? And why I am not getting error inside class but getting error in Execute Anonymous window?

List<Service_Contract_Products__c> coveredProducts = [SELECT Id,Installed_Product__c FROM Service_Contract_Products__c];
for(Service_Contract_Products__c coverProd : coveredProducts)
{
    if(coverProd.Installed_Product__r.Status__c != 'OPER - Operational')
    {
        System.debug(coverProd.Installed_Product__r.Status__c);
    }
}

2 Answers 2

3

Your query is missing the querying of the related record likely called Installed_Product__c. The field Installed_Product__c is just the Id of that record. To get fields from that object you will need to include _r references e.g. Installed_Product__r.Status__c in the query.

If you haven't already, I suggest you work through e.g. Write SOQL Queries, focusing particularly on the section about related records.

2
  • But why I am not getting error inside the class when I am using the same query?
    – Virat
    Jan 27, 2022 at 8:42
  • 1
    @Virat If the query never returned any rows, in the class case then the error would not occur. Otherwise it would.
    – Keith C
    Jan 27, 2022 at 8:45
2

Every field you want to read must be in the SOQL query.
The if condition checks the value of Installed_Product__r.Status__c, so that field must be added to the query in the first list of the snippet:

List<Service_Contract_Products__c> coveredProducts = [SELECT Id, Installed_Product__c, Installed_Product__r.Status__c FROM Service_Contract_Products__c];

If you need only the records related to the Installed Product that are not in 'OPER - Operational' status, you can add that condition in the WHERE clause:

SELECT Id, Installed_Product__c, Installed_Product__r.Status__c
FROM Service_Contract_Products__c
WHERE Installed_Product__r.Status__c != 'OPER - Operational'];

Keep in mind that time spent in SOQL query does't count toward CPU time limit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.