0

I've been working with Apex for a couple of months now and I still haven't figured this out. When does a SOQL query return a List of objects (even though it's just one object in the list) and when does it return an object?

For example, I have been using queries like this: [SELECT Id, Name FROM Account WHERE Name = :search] or [SELECT Value__c FROM System_Setting__c WHERE Name = :settingName]. And sometimes I can use an assignment directly to an object and some other times I need to use a list (even when I use a filter on Id or I use LIMIT 1 to make sure there's only one record to return.

1 Answer 1

8

A SOQL query will always return a list of sobjects. If you are assigning a query to a single sobject Apex will execute your query then attempt to assign to this sobject (unfortunately, if there are no elements in the returned query or more than one you will get an exception).

I find it's useful to always assign the query to a list of sobjects, then check to see how many elements the list contains afterwards, e.g.

List<Account> accountQuery = [SELECT Id, Name FROM Account WHERE Name = :search Limit 1];

if (accountQuery.size() == 1) { // execute code }

5
  • The thing I still don't quite understand is why sometimes the exception shows up as a compile error. Do you know that? Jan 7, 2013 at 12:17
  • I wouldn't expect a compile error here. They should only appear as runtime errors as Salesforce doesn't know the size of the list at compile time. Are you able to post up the code that gives you the compile error (and also the error message too) to see if I'm able to work out what it happening here?
    – Ben
    Jan 7, 2013 at 12:37
  • Could very well be that I'm mistaken. I haven't got an example right now, if I come across one again I'll show you. Maybe I'm just stupid :) Jan 7, 2013 at 12:41
  • 2
    Your code does in fact sometimes return an exception, one way to make sure it doesn't is by pre-initialising your list like so: List<sObject> list = new List<sObject>([SELECT Id, Name FROM sObject]; Now if your query returns 0 results you will still have a list to work with, no exception will be thrown, and you can perfectly do for(sObject sObj : list) without exceptions
    – pjcarly
    Jan 7, 2013 at 14:43
  • The query should instantiate the list even if it returns no results. I've got a similar bit of code in my VF page and I don't get any exceptions so I'm a little confused about this.
    – Ben
    Jan 7, 2013 at 15:42

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .