Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

following apex code

public String getLastUpdatedAt() {
String timeStr;
DatadoctorStatus__c last = [SELECT LastUpdated__c FROM DatadoctorStatus__c ORDER BY LastUpdated__c DESC LIMIT 1];
if (last == null){
    timeStr = 'Not yet updated.'; 
} else {
DateTime d = datetime.now();
    timeStr = d.format('MMMMM dd, yyyy hh:mm a z');
} 
return timeStr;
}

is giving me System.QueryException: List has no rows for assignment to SObject if there are no (zero) rows in DatadoctorStatus__c SObject.

share|improve this question
    
By the way this is expected behavior. If you attempt to assign query results into a single sObject instance, the query must always return exactly one record or it throws an exception. –  Peter Jan 9 '13 at 13:19

3 Answers 3

up vote 8 down vote accepted

Change your query to:

List<DatadoctorStatus__c> last = [SELECT LastUpdated__c FROM DatadoctorStatus__c ORDER BY LastUpdated__c DESC LIMIT 1];
if (last.isEmpty()){
        timeStr = 'Not yet updated.'; 
} else {
        DateTime d = datetime.now();
        timeStr = d.format('MMMMM dd, yyyy hh:mm a z');
} 
share|improve this answer

Get the response in a list and then further do you manipulations.

List<DatadoctorStatus__c> last = [SELECT LastUpdated__c FROM DatadoctorStatus__c ORDER BY LastUpdated__c DESC LIMIT 1];
if (last.size() == 0){
        timeStr = 'Not yet updated.'; 
} else {
        DateTime d = datetime.now();
        timeStr = d.format('MMMMM dd, yyyy hh:mm a z');
} 

You can also use last.isEmpty() function instead of last.size() == 0. isEmpty() Returns true if the list has zero elements.

share|improve this answer

It works as expected.You can do 2 things 1) wrap the query in a try catch block

try{ query} catch(exception ex){}

2) make the last as a list than havng it as an instance of datadoctorstatus_c then do for(datadoctorstatus_c l: last) { if(l== null){} }

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.