Monday 2 December 2013

Fetching Unique Record in Salesforce

It seems to be very easy to fetch unique record . You must be thinking Distinct keyword can be used for this. But saleforce does not support Distinct key word.
Another approach is we can us NOT IN key word for this. If we use this some error is there .
list<Account> listofAccounts = [SELECT id, Name 
                          FROM  Account 
                          WHERE Name NOT IN (SELECT Name FROM Account)];

You will face some error;
       COMPILE ERROR: Invalid bind expression type of SOBJECT:Account for column of type String

Because Inner & outer Query should have different object Type. That means if outer query is in Account then inner query must be in Contact.

Then the actual solution is we have to use GROUP BY key word.
GROUP BY returns aggregate result list.
lIST<AggregateResult> listofAccountsAggregateResult = 
                            [SELECT Name
                                                         FROM  Account
                                                         GROUP BY Name];
It will return unique record of Accounts

2 comments:

Unknown said...

NIce .. Excellent... Awesome Post...


Keep posting... :)

Asish Kumar Behera said...

Thank you Jyotirmaya Rath, I will