Search code examples
salesforceapex-codesoql

Check for existence or catch exception?


I want to update a record if the record exists or insert a new one if it doesn't.

What would be the best approach?

Do a Select Count() and if comes back zero then insert, if one then query the record, modify and update, or should I just try to query the record and catch any system.queryexception?

This is all done in Apex, not from REST or the JS API.


Solution

  • Adding to what's already been said here, you want to use FOR UPDATE in these cases to avoid what superfell is referring to. So,

    Account theAccount;
    Account[] accounts = [SELECT Id FROM Account WHERE Name = 'TEST' LIMIT 1 FOR UPDATE];
    if(accounts.size() == 1)
       theAccount = accounts[0];
    else
       theAccount = new Account();
    
    // Make modifications to theAccount, which is either:
    // 1. A record-locked account that was selected OR
    // 2. A new account that was just created with new Account()
    
    upsert theAccount;