[SalesForce] System.QueryException: List has no rows for assignment to SObject

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.

Best Answer

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');
} 
Related Topic