1

Is it possible to select only fields using SOQL? I mean to select fields without selecting whole SObjects?

For example, is it possible to select a List<Name> of names of accounts, such that accounts have Rating = 'Warm'?

I know about

List<Account> = [
    SELECT Name
    FROM Account
    WHERE Rating = 'Warm`
];

But I would like my list to have only names.

6

Not directly. You need to write your own loop e.g.:

List<String> names = new List<String>();
for (Account a : [
        select Name
        from Account
        where Rating = ‘Warm’
        order by Name
        ) {
    names.add(a.Name);
}
2

In the general sense, no, you cannot do this. The single exception to this by way of ID types using AggregateResult:

Set<Id> accountIds = new Map<Id, AggregateResult>([
  SELECT AccountId Id
  FROM Opportunity
  GROUP BY AccountId]).keySet();

This works by aliasing the lookup field to the special value Id (case sensitive), which we briefly turn in to a map, and get the key set for that map.

Obviously, this will not work for any other type of field, in which case you'll have to use a for loop, as mentioned by Keith's answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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