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
Krishna Prasad K PKrishna Prasad K P 

SOQL query in Apex Trigger throws error (System.QueryException:no rows for assignment) !!

Hi,

I have a 'before insert trigger' on Opportunity. The trigger contains an SOQL select query which returns(may or may not) one record and assigns to an Opportunity variable.
The query statement is:
"Opportunity Opp_variable = [SELECT id,Counter__c,AccountId FROM Opportunity where (AccountId=:New_record.AccountId AND Counter__c!=null) ORDER BY Counter__c DESC LIMIT 1];"

After this statement I have "if(Opp_variable!=NULL)..statements",
But I get the Error message:
"System.QueryException: List has no rows for assignment to SObject"
This is caused because there is no record satisfying my query conditions.. But it should have returned NULL.. ?

Why Am I getting this error..!! SOQL query cannot return null value??

How can I sove this issue..? Please help me

Thanks in Advance..
Krishna
Best Answer chosen by Admin (Salesforce Developers) 
Vijay RautVijay Raut
Hi Krishna,

Instead of using "if(Opp_variable!=NULL)", you can use "if(Opp_variable.size() > 0)".
Try out this, and i think you will be able to get rid of your error.

The reason is, List is something like array, which is not null once initialised, but has the size 0, if there is no elements.

Thanks
V. R.

All Answers

Vijay RautVijay Raut
Hi Krishna,

Instead of using "if(Opp_variable!=NULL)", you can use "if(Opp_variable.size() > 0)".
Try out this, and i think you will be able to get rid of your error.

The reason is, List is something like array, which is not null once initialised, but has the size 0, if there is no elements.

Thanks
V. R.
This was selected as the best answer
SuperfellSuperfell
If you assign a query result to a single object, the query MUST return a 1 row, no more, no less. If it might return something other than 1 row, you should assign it to an array, then examine the array length.
Krishna Prasad K PKrishna Prasad K P
Wow..!!
I used array to capture the record, and it works well..!!!!
Thanks a lot Vijay and Simon.. :-)

Regards,
Krishna
hector.asp2hector.asp2

Hi Vijay Raut

 

when i trying to use your way, i again getting an error :

 

Error: Compile Error: Method does not exist or incorrect signature: [SOBJECT:Account].size() at 

 

code : 

 

Account   TempAccount =[select Id from Account  LIMIT  1];

   if(TempAccount.size()>0) 

{

.... 

 

 

ArkadiuszWArkadiuszW

You have to make an array:

 

Account[] TempAccount =[select Id from Account LIMIT 1]; if(TempAccount.size()>0) { TempAccount[0].id ....//any code}