+ 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) {

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.