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

I’ve run across this oddity a few times. When you construct a SOQL query thusly

Account a = [select id from account where id = '01pL00000000XXX'];

And if the ID returns no rows, instead of setting the resulting Account record to null, it throws a System.QueryException. If there is a row returned, it works great.

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

I can’t imagine why this occurs. In effect, this forces the best practice to do one of the following:

  1. Surround your query with a try/catch block:

    try {
      Account a = [select id from account where id = '01pL00000000XXX'];
    }
    catch (System.QueryException e) {
      System.debug('caught ya!');
    }
  2. Return a list of results instead of a singular result:
    List<Account> a = [select id from account where id = '01pL00000000XXX'];
    if (a.size() == 0) {
      System.debug('nothin!');
    }
This entry was tagged , , . Bookmark the permalink.