Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 1

up vote 6 down vote accepted

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 }

share|improve this answer
    
The thing I still don't quite understand is why sometimes the exception shows up as a compile error. Do you know that? –  Lex Jan 7 '13 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 '13 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 :) –  Lex Jan 7 '13 at 12:41
1  
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 –  PJC Jan 7 '13 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 '13 at 15:42

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.