+ Start a Discussion

Prevent duplicate records on insert

  • Hi Guys,

I have a requirement where i need to prevent duplicate records from being inserted upon insert or update.


For this i have a created a formula field that concatenates 2 fields and made this as unique.


I know this works when the user tries to insert a duplicate from UI, but i would like to know if this will also help me on bulk insert, i dont want the whole transaction to get rolled back. Is trigger the only way out? If yes, a sample code will be helpful.







You can store the records in a set and then copy them to list and insert that list.





Bulk inserts that use the allOrNone header (with a value false) can error just on the records that were duplicates (based on an addError function call or validation rule). If allOrNone is set to true, then the entire transaction would instead be aborted. You should take a look at the rules for how allOrNone works.



   This is the code which prevents duplicate entry in Lead Object . I hope this may help you..


trigger leadDuplicatePreventer on Lead
(before insert, before update) {

Map<String, Lead> leadMap = new Map<String, Lead>();

for (Lead lead : System.Trigger.new) {

// Make sure we don't treat an email address that isn't changing during an update as a duplicate.

if ((lead.Email != null) &&
(System.Trigger.isInsert ||
(lead.Email !=
System.Trigger.oldMap.get(lead.Id).Email))) {

// Make sure another new lead isn't also a duplicate

if (leadMap.containsKey(lead.Email)) {

lead.Email.addError('Another new lead has the '
+ 'same email address.');

else {

leadMap.put(lead.Email, lead);


// Using a single database query, find all the leads in
// the database that have the same email address as any
// of the leads being inserted or updated.

for (Lead lead : [SELECT Email FROM Lead
WHERE Email IN :leadMap.KeySet()]) {

Lead newLead = leadMap.get(lead.Email);

newLead.Email.addError('A lead with this email '
+ 'address already exists.');


Did this answers your questions...if so please mark it solved