Does one use savepoints in triggers?

It’s not clear to me. Suppose I write an after update trigger on opportunity to update some related accounts and then contacts.
Now I lets suppose that I had luck with the accounts but the second dml – on contacts failed.
If I get an exception and do not handle it no data will be committed to the database right? No changes to applied to Opportunities or accounts will be saved. right?
So no need for savepoints and rollbacks it exceptions aren’t caught and handled.
THANK YOU @sfdcfox

This should go into comments but they are too short. I know my questions are a bit academical but I have certification on my radar in near future. Best way to learn coding is to see other people’s code (good or bad). One doesn’t get enough of best worst/practice examples with Apex.
Maybe this will help other people.
I’ve never seen Database.operations() in triggers. And I’ve read a few books by famous names.
People prefer the standard update records syntax. What I always see is

{ process opportunities and do opp.addError() }
update accounts;
update contacts;

You are absolutely right it makes no sense to fail a whole batch because of 1 record.
Are you saying one can do the below without a need of savepoints? What if I get no errors on account but I fail on contacts. I add an error to the opportunity – it’s not updated, contact has already failed to update but the account changes get committed right? or not?

{ process opportunities and do opp.addError() }
saveResult res = database.update(accounts,false);
if( res contains error){
add error from account to related opportunities;
res = database.update(contacts,false);
if( res contains error){
add error from contacts to related opportunities;


You should handle exceptions in triggers. If you don’t, then your trigger won’t be bulk safe, meaning any failure in a batch of up to 200 records will kill the entire batch, which is usually undesirable.

However, within a trigger, there is no need for explicit save points. Instead, handle the DML failures, and use addError on any records where the recursive update failed, so it can be handled gracefully.

For example, in an opportunity trigger that updates related accounts and contacts, if either update falls, add that error to the opportunity that was related to the failed contact, and the system will try the trigger again minus that one opportunity if the allOrNone flag is set to false. This will allow partial saves.

Source : Link , Question Author : user682217 , Answer Author : sfdcfox

Leave a Comment