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
SFDC 2017SFDC 2017 

Check if record already exists or not if it is not then create new record

Hi All,

I have written a batch class with the below scenario.
if (ObjectName==Account)
{ need to query account  records
else if (ObjectName =Contact )
{ Query Contact records)
So i will get either account or contact records in scope and in execute method i will create records for other custom object means if it is account it will insert with account Id in the new custom object and if Contact contact Id in the new object .Right now it is captuirng the Id into another custom Object but the problem is whenever i am executing it is capturing the same .

So here i want to eliminate the creation of duplicates means if the Record Id(Acc or con Id already in the new custom object then it should not create new record if the record is not existing then create new record with the Acc or Con Id

My Code:
  global void execute(Database.BatchableContext BC, List<SObject> scope)
        Map<id, Custom Object> CustomMap= new Map<id,Custom Map>();
         for(Sobject obj: scope)
                Custom Object cm= new Custom Object();
                 cm.Recordt_ID__c =obj.Id;
                  CustomMap.put(Cm.Object_ID__c, cm);
            Database.SaveResult[] InsertResult = Database.insert(CustomMap.values(),false);

So here how i will check if there is already a record with same Object Id is there then it should not insert if it is not there it should create new custom object Record.Any one please guide how to do this

Thanks in advance
Tejpal KumawatTejpal Kumawat
Hi Archu,

You need to make one more SOQL on Custom object that will give you results comparision for new records vs old records, On the basis of that condtion you can eaisly eliminate existing records.

Tej Pal Kumawat
Skype : tejpalkumawat1991

If this answers your question mark Best Answer it as solution and then hit Like!
Jim JamJim Jam
Not sure if it will work, but maybe try ...

Database.SaveResult[] InsertResult = Database.upsert(CustomMap.values(),'',false);
Simha YadavSimha Yadav

you can use this code 

trigger xyz on Account (before insert){
List<account> ac=[select id,name form account];
for(account acc:ac)
ac.adderror('you can enter duplicate record');

SFDC 2017SFDC 2017
Thanks @simha.I have written Batch class and it is working now.i am  not using Trigger.
Pavan Kumar S 9Pavan Kumar S 9

Hi, I have the same kind of issue and I need help in it.
data = { 'Account__c': "001", 'Name': "Ram", 'Certifications_Present__c': "undamentals" }

I will create this data and next time if Ram with other certification comes in I need to update it rather than creating it. I use Python for doing so. 

Can anyone suggest me a solution please.