CRT-450 practice question 6 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

The Apex syntax sObject variable = [SOQLquery]; is specifically designed to assign a single record to an sObject variable. If the SOQL query returns more than one record, the Apex runtime environment throws a System.QueryException with the error message "List has more than 1 row for assignment". If this exception is not handled within a try-catch block, it is considered an unhandled exception, which immediately terminates the transaction and prevents further code execution.

References

1. Salesforce Apex Developer Guide

"SOQL and SOSL Queries": The guide explains that assigning a query result to a single sObject variable is only valid if the query returns exactly one record. It states

"If the query returns no records

a System.QueryException is thrown... Likewise

if the query returns more than one record

a System.QueryException is thrown."

Reference: Salesforce Apex Developer Guide

Chapter 3: "Database & DML"

Section: "Writing SOQL Queries".

2. Salesforce Apex Developer Guide

"Exception Class and Built-In Exceptions": This section documents the System.QueryException. It is described as an exception that is thrown for errors that occur during SOQL or SOSL query execution

including when a query that is expected to return a single row returns multiple rows.

Reference: Salesforce Apex Developer Guide

Appendix: "Apex Language Reference"

Section: "Exception Class and Built-In Exceptions".

Scroll to Top