I am trying to query records and collect them in a Set as below

Set<abc__c> a = [select id from abc__c limit 2];

but getting the following error Illegal assignment from LIST to SET.Can't I collect the result of a query in Set ?

2 Answers 2


There is simple way:

Set<Account> acc = new Set<Account>([SELECT id from Account]);

You cannot type cast a List<sObjectType> to Set<sObjectType> just by query assignment, pass it to Set constructor instead.

//Fetching all account in map
 Map<id,abc__c> aMap = new Map<id,abc__c>([select id from abc__c limit 2]);

 Set<Id> a=aMap.keyset();

You cannot directly collect in set and using maps save script statements and avoiding loops .

  • 3
    In the second statement keySet() method will only return the ID's and not set of sobject. I think the second statement will error out
    – Sam
    Sep 17, 2013 at 10:04

You must log in to answer this question.

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