PDI practice question 27 of 30

Given the following Apex statement: Account myAccount = [SELECT Id, Name FROM Account); What occurs when more than one Account is returned by the SOQL query?

Full set: 201 questions
Answer options
A: The variable, myaccount, is automatically cast to the List data type.
B: An unhandled exception is thrown and the code terminates. Correct answer
C: The query fails and an error is written to the debug log.
D: The first Account returned is assigned to myAccount.
Correct Answer:
B. An unhandled exception is thrown and the code terminates.
Explanation

In Apex, when a SOQL query is expected to return a single record and is assigned directly to a single sObject variable (e.g., Account myAccount = [...]), the query must return exactly one record. If the query returns more than one record, the Apex runtime cannot assign the resulting list to the single sObject instance. Consequently, it throws a fatal System.QueryException with the message "List has more than 1 row for assignment to SObject". If this exception is not caught within a try-catch block, it becomes unhandled, halting the transaction and terminating the code execution.

Why Incorrect

A. Apex is a strongly typed language and does not perform automatic type casting from a list of sObjects to a single sObject variable.
C. While an error is logged, the primary event is a thrown exception that terminates the transaction, which is a more precise and critical outcome.
D. Apex does not implicitly assign the first record from a multi-record result set to a single sObject; this action results in a runtime exception.

References

1. Salesforce Apex Developer Guide, "Working with SOQL Query Results": "If the query returns a single record, the result can be assigned to a single sObject variable... Likewise, if the query returns more than one record, a System.QueryException is thrown."

2. Salesforce Apex Developer Guide, "Exception Class and Built-In Exceptions": The documentation for QueryException states it is thrown for "A SOQL query that returns no records or more than one record when the result is assigned to a single sObject variable."

3. Trailhead, Apex Basics & Database Module, "Write SOQL Queries" Unit: "To retrieve a single record, you can assign the result of a SOQL query to a single sObject variable... If the query returns no records or more than one record, a runtime error occurs."

Scroll to Top