function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Renato Garofalo 13Renato Garofalo 13 

query with condition on lookup field

I have a query inside a trigger and one of the conditions is that a reference field (lookup) is not null. My query is:
List<Contract> contratti=[Select Id,Opportunitl__c from Contract 
        where Id IN: Trigger.new AND Opportunitl__c !=null ];

where Opportunitl__c is the reference field, but it's not working. The list "contratti" contains Contracts with an empty Opportunitl__c. What is wrong in this query?
Alexander TsitsuraAlexander Tsitsura
Hi Renato,

You can avoid using soql in this situation. You can iterate through Trigger.new collection and pick with specific criterions.
List<Contract> contratti = new List<Contract>();
for (Contract c : (Contract[]) Trigger.new) {
    if (null != c.Opportunity__c) {
        contratti.add(c);
    }
}


Thanks,
Alex
Head In CloudHead In Cloud
Hi Renato, 

There is nothing wrong with the code you are using. It should not contains contracts with empty Opportunitl__c. The problem maybe somewhere else.