+ Start a Discussion
SabrentSabrent 

Does SOQL always have to return some result?

SOQL returns 0 rows, and gives me System.ListException: List index out of bounds: 0

I thought  checking for null should get rid of the error, but no, it still errors out.

 

list<Object__c> obj = new list<Object__c>();

 

obj  =  [select ..........];

 

(if obj != null) {

 

      //get into this block

}

 

update obj[0] ;

 

Does SOQL always have to return some result?

Best Answer chosen by Admin (Salesforce Developers) 
SLockardSLockard

No, it can return nothing, but when it does, you won't be able to update the first element, because there is nothing there!

So change your code like this :

list<Object__c> obj = new list<Object__c>();

 

obj  =  [select ..........];


(if obj != null) {
      //get into this block
      update obj[0] ;
}

 

 

All Answers

SLockardSLockard

No, it can return nothing, but when it does, you won't be able to update the first element, because there is nothing there!

So change your code like this :

list<Object__c> obj = new list<Object__c>();

 

obj  =  [select ..........];


(if obj != null) {
      //get into this block
      update obj[0] ;
}

 

 

This was selected as the best answer
SabrentSabrent

thanks.

 

I tried obj.size() > 0 and moved the update as you suggested, yet getting same error.

 

list<Object__c> obj = new list<Object__c>();

 

obj  =  [select ..........];


(if obj.size()>0) {
      //get into this block
      update obj[0] ;
}
SLockardSLockard

Is this in a trigger, or test method, or class?

SabrentSabrent

Thanks. it worked.