1

My code is pulling through Opportunity records where the StageName is equal to 'Closed won - Signed Contract' or 'Closed Lost'. However it shouldn't be pulling through these records. What is wrong with my query?

 listOpportunity = [SELECT Id, OwnerId,Name,Owner.FirstName,(SELECT Id, Product2.Name FROM OpportunityLineItems
                                                            WHERE Product2.Convert_to_Service_Catalogue_Emailed__c = FALSE
                                                            AND Product2.Convert_to_Service_Catalogue_Initiated__c = TRUE)
                                                            FROM Opportunity
                                                            WHERE (StageName != 'Closed Won - Signed Contract' OR StageName != 'Closed Lost')
                                                            AND Id in
                                                                       (SELECT OpportunityId FROM OpportunityLineItem
                                                                        WHERE Product2.Convert_to_Service_Catalogue_Emailed__c = FALSE
                                                                        AND Product2.Convert_to_Service_Catalogue_Initiated__c = TRUE)];

1 Answer 1

8

From a logical perspective, any time you have a statement of the form X != A || X != B, it will always return true unless A = B. For instance, if your StageName equals "Closed Lost", then it does not equal "Closed Won - Signed Contract". The StageName is always going to not match one of those values, since it can't be both at the same time. So that OR clause will select every record.

When matching on one field, use IN and NOT IN operators.

StageName NOT IN ('Closed Won - Signed Contract', 'Closed Lost')

If you really wanted separate clauses, AND would be the correct operator to join them, since it should be X != A && X != B, which is true whenever X does not match A and does not match B.

StageName != 'Closed Won - SignedContract' AND StageName != 'Closed Lost'

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .