+ Start a Discussion
pcave_jrpcave_jr 

What does a SOQL query return if no row is found

How do I check if a valid Contact is returned from a query like this in Apex.

 

Contact o = [SELECT c.Id, Email, LastName, FirstName, MailingCity, HomePhone, MailingState, MailingStreet, MailingPostalCode, AccountId, Source_Code__c, Drupal_User_Id__c FROM Contact c WHERE c.Email = :n.Email AND c.Id != :n.Id limit 1];

 

How do I check to see if o is a populate Contact object.

Duncan_IdahoDuncan_Idaho

 

Contact[] oa = [SELECT c.Id, Email, LastName, FirstName, MailingCity, HomePhone, MailingState, MailingStreet, MailingPostalCode, AccountId, Source_Code__c, Drupal_User_Id__c FROM Contact c WHERE c.Email = :n.Email AND c.Id != :n.Id limit 1];

Contact o;
if(oa.size()>0)
{
  o = oa[0];
}

 

 

mikefmikef

The query will return a QueryException.

Duncan_IdahoDuncan_Idaho

You'll get "List has no rows to assign to sObject".

mikefmikef

Well if you want to be exact then you get back.

 

 

20.0 APEX_CODE,DEBUG
Execute Anonymous: Contact c = [select id from Contact where Id = '123456789012345'];
13:14:27.136|EXECUTION_STARTED
13:14:27.136|CODE_UNIT_STARTED|[EXTERNAL]|execute_anonymous_apex
13:14:27.179|EXCEPTION_THROWN|[1]|System.QueryException: List has no rows for assignment to SObject
13:14:27.179|FATAL_ERROR|System.QueryException: List has no rows for assignment to SObject

AnonymousBlock: line 1, column 13
13:14:27.179|CODE_UNIT_FINISHED|execute_anonymous_apex
13:14:27.179|EXECUTION_FINISHED

 

 

pcave_jrpcave_jr

Hm. Getting some inconsistent answers. So do I expect to catch an exception or can I assign it to a list and check the size?

Duncan_IdahoDuncan_Idaho

Using the code snippet I posted will work.

tharristharris

You will only get the exception if you attempt to assign the results of the query to a single value rather than a list. In the example in your first post there would be an exception if no contact was found because you are assigning to a Contact variable.

 

For example, this causes an exception when there are no results:

 

Account res = [select name from account where createddate > 2012-12-31T23:59:59Z limit 1]; // no results, causes exception

 

While this does not:

 

List<Account> res = [select name from account where createddate > 2012-12-31T23:59:59Z];

System.debug(res.size()); // Outputs 0.

DownstairsBDownstairsB

Either.  Depends on your preference.

Vaishali mehtaVaishali mehta
Hi Duncan_Idaho,
I tried your code. 
Getting the error "Method does not exist or incorrect signature: void size() ".
Can you suggest something?
Phil WPhil W
@Vaishali mehta, did you make sure you made the variable you are assigning the result to into an array like Duncan_Idaho showed?