Writing an apex trigger that fires on on before Insert. However, if a record exists based on certain criterion I would like to change that insert action into an update action. I understand I can prevent the insert from happening by issuing an error

    account.name.addError('Duplicate in name'); 

but that is NOT what I want to do. I want to silently update where possible. Is there a way to accomplish this on a before insert trigger. Any examples of how we could change the insert operation to upsert within a trigger?

This is the trigger code and without throwing an error how do we change the insert that would happen after the trigger fires to an update?

trigger addAccountTrigger on Account (before insert) {
        //how do we do an update and prevent insert here?
  • Simply do a SOQL query on account and check if any account exists with the details provided for new account. If any account matches all the details, then change the dml operation to update instead of insert. Commented Aug 20, 2018 at 10:18
  • 7
    Doing so can be done, but requires deleting records post-insert. It'd be a lot better to use the upsert command instead.
    – sfdcfox
    Commented Aug 20, 2018 at 10:19
  • Any example of code within a trigger where I can change dml operation to update/upsert?
    – user275157
    Commented Aug 20, 2018 at 11:17

1 Answer 1


As there is no way to prevent insertion of record with successful transaction commit, if you add error in current record to prevent insertion it will roll back your update operation as well.

You can do this by implement after insert, inside this query the existing record and update that whatever you want

And than delete the current record.

So this will update the existing record

Using below code you can delete current record.

delete [ select Id from account where id in :Trigger.new];
  • But the UI will show an error. I need a silent update. How would I achieve this?
    – user275157
    Commented Aug 22, 2018 at 10:32
  • I have updated the comment. Future will not work in this scenario and this will also work silent update. Commented Aug 22, 2018 at 10:34
  • Above approch worked for you? Commented Aug 22, 2018 at 13:50
  • Yes...hopefully there is a way to avoid creation / deletion in the future.
    – user275157
    Commented Aug 26, 2018 at 3:25

You must log in to answer this question.

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