Want to restrict the duplicate account. I tried with the below code. It is working fine on insert and not working on update. When I edit any account record it is giving error as duplicate. Can any one help me out what changes I need to make in my code.

Here is my trigger:

trigger DuplicateAccount on Account (before insert,before update) {
    Set<string> accname = new Set<string>();
    Set<string> duplicateAccIds = new Set<string>();

    for(account acc:Trigger.new){
    list<account> duplicateAcclist = [SELECT id, name FROM account WHERE name=:accname];
        for(account dup:duplicateAcclist){
    for(account a:trigger.new){
        if(a.name != null){
                a.addError('Record already exist with same name');

1 Answer 1


The problem that you have is the fact that you are actually querying the same account at update.

So, for example:

  • You have an account(A1) with name testAcc and you update some field
  • Trigger fires on update
  • You query accounts WHERE Name = 'testAcc'
  • Aaaaand... You get that A1 in your query!
  • As the result, you will addError() on A1 which will prevent it from being updated

So you should make sure that that same account A1 will not be in your query, otherwise you will always get an error(except for when you change the name of the account).

Also, why don't you use standard duplicate management? Don't forget: Code that you do not write is the code you do not have to maintain

  • Ok Thanks for your reply.. So how can I do it on update..?
    – user41260
    Commented Feb 1, 2017 at 7:35
  • 2
    @user41260 Use duplicate management. There's no need to do this in code any longer.
    – sfdcfox
    Commented Feb 1, 2017 at 7:53
  • Thanks a lot yar.. I just gone through that duplicate management. Its really help me alot. Thanks again guys.
    – user41260
    Commented Feb 1, 2017 at 10:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .