function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion

How to prevent duplicates from inserting?



I have to insert unique records(i.e remove the duplicates) from some  custom field (say employee_id) in one custom object into another custom field in another custom object.

Can anyone share some working code? It will be helpful.




Shailesh DeshpandeShailesh Deshpande
Here's a link with a very nice example to avoid duplicates:

Hey thanks.

I had gone through it already. But i am not able to get unique records from one custom object and insert into another custom object. So can u help me with some code.





There are several ways to get a distinct collection.  You could use an AggregateResult SOQL query;  if its a relatively modest amount of results, you could query for the full list then manually sort them yourself in Apex, maybe put them in a Set:


Set <ID> uniqueIDs = new Set <ID> ();

for (Obj_A__c nextObj : [Select employee_id From Obj_A__c]) {




for (ID nextID : uniqueIDs) {

    // do something with Obj_B__c



Aggregate queries have been covered in many threads, governor limits can be an issue if you are talking about 50k+ results: