I am trying to use the result of a query to be used as In another query but I am getting an error. How do I solve this?

trigger CopyChecklistIntoLegitimation on Legitimation__c(after insert){

  //Get the related account's legalstructure of the legitimation

Account queriedLegalStructure = [Select LegalStructure__c from Account Where Id in 
                                (Select Account__c from Legitimation__c Where Id in 
List<CheckListTemplate> listTemp = [Select name from ChecklistTemplate__c Where Entity__c = 'legitimation' And LegalStructure__c IN: queriedLegalStructure.LegalStructure__c];

My error is when I am trying to save, I get IN operator must be used with an iterable expression

  • What is the error message? Please edit your post to include it verbatim. – Adrian Larson Apr 25 '19 at 4:46

You can only use the IN operator straight away (no added collections) if you are filtering on Id values. If you are filtering on any other field, you have to aggregate the values into a collection and filter on that.

Set<String> legalStructures = new Set<String>();
for (Account record : [/*first query*/])
List<CustomObject__c> records = [
    SELECT ... FROM CustomObject__c WHERE ... AND LegalStructure__c IN :legalStructures
  • But any time I only get one record associated with the legalstructure on account so I assume I do not need a collection – user3920709 Apr 25 '19 at 4:53
  • That is a faulty assumption. Technically you can assign a query result to a single record, but it is more brittle and will lead to unnecessary errors. Unless you are dead certain the result cannot be empty or have multiple records, you simply can't write the code that way. – Adrian Larson Apr 25 '19 at 4:57
  • Thanks for enlightening me – user3920709 Apr 25 '19 at 5:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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