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, 
        FROM Entity__c 
        WHERE Id = :salesId];      
      else {
        List<Entity__c> entity = [SELECT Status__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..

ps: I am still learning to write APEX, I am sure I am missing some basics here but cannot figure it out.

1 Answer 1


You need to declare List<Entity__c> entity = new List<Entity__c>(); above if-else condition. The code that runs after it does not see variables that were declared in if-else block.

  • when I do that, I get duplicate variable error Sep 9, 2020 at 4:25
  • 1
    that worked, I used a list for the variable even after declaration which is why I was getting that error. Sep 9, 2020 at 4:28
  • The industry term for this is "variable scope". The "scope" of a variable declared inside a block of code (i.e. code contained within curly braces, { and }) is limited to that block and any amount of blocks nested inside of it. That's why we can access variables declared in a method (probably the most common "block" we see) inside of the block(s) attached to an if/else statement.
    – Derek F
    Sep 9, 2020 at 11:37

You must log in to answer this question.

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