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
Kevin OcieKevin Ocie 

IF-Else not working

I am trying to filter records based on the below if-else condition in apex code

if (salesId != NULL) { List<Entity__c> entity = [SELECT Status__c, Item__r.Vendor_ID__c FROM Entity__c WHERE Id = :salesId]; } else { List<Entity__c> entity = [SELECT Status__c, Item__r.Vendor_ID__c FROM Entity__c WHERE Item__r.Vendor_ID__c = :vendorId]; }


Error: Variable does not exist entity


Is it even possible to write SOQL query in IF-Else like this into the same variable? I tried to look for example where SOQL is written in If-else and could not find any..

Thanks.
AnudeepAnudeep (Salesforce Developers) 
Hi Kevin - I created a custom object called Entity__c in my org and executed your code in execute anonymous window in the developer console and did not receive any errors. 

I don't think there is an issue with the code. SOQL query in if and else is allowed. Are you sure the issue is coming from this block of code?
 
if (false==true) { 

List<Entity__c> entity = [SELECT id FROM Entity__c]; } 

else

{ List<Entity__c> entity = [SELECT id FROM Entity__c]; }

 
Kevin OcieKevin Ocie
Yes it is coming from the code as mentioned earlier.
AnudeepAnudeep (Salesforce Developers) 
Can you try removing your bind variables and let me know if that works? A similar question is answered here