Fix a query that finds no rows
Debug it · Intermediate · 10 min · Runs in your Salesforce Developer org · Apex Path
Scenario. A screen shows the phone of the Account a caller names. It crashed for a caller whose Account had been renamed.
A lookup method works until an Account is missing, then throws List has no rows for assignment to SObject. Make it return null instead.
What you will learn
Assigning a query straight to one record is a gamble:
Account match = [SELECT Phone FROM Account WHERE Name = :name LIMIT 1];
When nothing matches, Apex throws List has no rows for assignment to SObject. There is no null to check. The safe shape is to query into a List, which is empty when nothing matches, and check isEmpty() before you read [0].
Gotcha. LIMIT 1 protects you from too many rows, not from zero rows.
The task
Fix phoneFor so it returns null when no Account has that name, instead of throwing.
Examples:
- Account
Northwindwith Phone555-0100→555-0100 - no Account named
Nobody→null - Account
Quietwith no Phone →null
Requirements:
- Query into a
List<Account>instead of oneAccount. - Return null when the list is empty.
- Return the Phone of the first match otherwise. Keep
LIMIT 1. - Do not wrap the query in try and catch. Fix the cause, not the symptom.
Starter code
public class AS_1603269E2B24_AccountPhones {
public static String phoneFor(String accountName) {
Account match = [
SELECT Phone
FROM Account
WHERE Name = :accountName
LIMIT 1
];
return match.Phone;
}
}
When it passes
A matching Account gives its Phone. No match, a blank name, or a match with no Phone all give null, with no exception.
You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.