+ Start a Discussion

Delete duplicate objects



I have an object with the following data {name, location, distance}.  I want to identify all the objects having the same name and location and delete all but the one with the shortest distance.  Would this be possible using SOQL?


If not would it be possible to write a trigger to avoid the creation of objects if they have the same name and location of an existing object?




I was hoping to do something like this:


Course c = [SELECT c1.name__c, c1.location__c FROM Course__c c1, Course__c c2 WHERE c1.distance__c < c2.distance__c AND c1.name__c = c2.name__c AND c1.location__c = c2.location__c];


But I get an error.


You can't do SQL style joins in SOQL.


You can get values from lookups/parent objects, and you can also query child rows (as long as there is a master-detail relationship defined on the child object), i.e.


You can have:


Course__c (chlid of School__c)


You can do this:

select Id, School__c.Name from Course__c


Or you can do this:

select Id, Name, (Select Id, Name from Courses__r)

from School__c


If you don't want multiple courses with the same name and location, you would have to write a trigger.

Before writing your trigger, I'd have a formula field which concatenates name and location.  (We'll call it Course_Key__c)

Create a trigger that fires on before insert or before update:

Set<String> courseKeys = new Set<String>();
for (Course__c course : Trigger.new) {
Set<String> existingCKeys = new Set<String>();
for (Course__c existingCourse : [select Id, Course_Key__c from Course__c where Course_Key__c in :courseKeys and Id not in :Trigger.new]) {
for (Course__c course : Trigger.new) {
    if (!existingCKeys.contains(course.Course_Key__c)) {
        course.addError('location/name combination already exists');




Naveen NelavelliNaveen Nelavelli

for existing records  you can write some code and excute it in anonymous window....


List<Course__c> list 1=[SELECT  name__c, location__c,id FROM Course__c ];

List<Sobject> delList=new List<Sobject>();

for(Course__c c:list1){

for(Course__c z:list1){

if(z.name__c=c.name__c and z.location__c=c.location__c){







//dml statement