function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Mayur Naidu 17Mayur Naidu 17 

Can a database method invoke Apex Trigger?

Hello, I wanted to know if we use a Database.update() method in an Apex class for an sObject, does this update invoke 'before update' Apex trigger on that sObject?

Thanks for you help.
Agustin BAgustin B
Hi Mayur, yes it does. It will invoke a before update and after update available for that sObject.

If it help you please mark this answer as correct, it may help others.
AbhishekAbhishek (Salesforce Developers) 
Hi Mayur,

yes, it can be done.

For your reference, you can check the below articles,

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers_syntax.htm

https://mindmajix.com/salesforce/how-to-create-sample-apex-trigger-in-salesforce


I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks!
MoonpieMoonpie
Hi Mayur,

I agree with the two before me.  I just wanted to add that this is how we test triggers with our test classes and methods - we create test data and insert it (and update it if necessary) because we know it will fire the triggers.
Mayur Naidu 17Mayur Naidu 17
Thank you for your reply. If we have a scenario where a trigger is calling an Apex class with database.update method, based on your answer, won't it be stuck in an infinite loop assuming database.update method always has records to be updated?
MoonpieMoonpie
Mayur,

From the 6th paragraph (actually it's the entire paragraph) from the first page of the Triggers section of the Apex Developer Handbook (https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers.htm?search_text=triggers):

"Triggers can also modify other records of the same type as the records that initially fired the trigger. For example, if a trigger fires after an update of contact A, the trigger can also modify contacts B, C, and D. Because triggers can cause other records to change, and because these changes can, in turn, fire more triggers, the Apex runtime engine considers all such operations a single unit of work and sets limits on the number of operations that can be performed to prevent infinite recursion. See Execution Governors and Limits (https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_gov_limits.htm)."

Also, you can check around the "interwebs" where folks have come up with ways to ensure that a trigger fires once and only once in certain circumstances/use cases.