[SalesForce] Using same Dml as used in before and after trigger

i am new to salesforce
my code snippet is

trigger AccountTrigger on Account (before update) 
{
   List<Account> ac = [SELECT id FROM Account WHERE id NOT in : trigger.newMap.keySet()];
   update ac;  
}

it is showing error

AccountTrigger: execution of BeforeUpdate caused by:
System.DmlException: Update failed. First exception on row 0 with id
001i000000rN9LbAAK; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY,
AccountTrigger: execution of BeforeUpdate caused by:
System.DmlException: Update failed. First exception on row 0 with id
001i000000f3QDpAAM; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY,
AccountTrigger: execution of BeforeUpdate caused by:
System.DmlException: Update failed. First exception on row 0 with id
001i000000rN9LbAAK; first error: SELF_REFERENCE_FROM_TRIGGER, Object
(id = 001i000000rN9Lb) is currently in trigger AccountTrigger,
therefore it cannot recursively update itself: []
Trigger.AccountTrigger: line 105, column 1: [] Trigger.AccountTrigger:
line 105, column 1: []: Trigger.AccountTrigger: line 105, column 1

my main motto behind writing this code is to know what all are the consequences if we use same dml operation inside the trigger on the same object that has invoked the trigger(in this case its update)
like here it is trigger on account on before update
and i am updating the same object inside the trigger

Thanks in advance 🙂

Best Answer

As you are describing in your question there is no need of much explanation what is going on here. You are trying to update an account in the event of before update which tries to fire the trigger again and again.
This is not accepted and if you really need to do an update in a before trigger(into the triggering object) you can just set that field. It will be effected when the real update happens.

trigger AccountTrigger on Account (before update) 
{
   for(Account a : [SELECT id FROM Account WHERE id NOT in : trigger.newMap.keySet()])
      a.FieldName = value;   // no need of DML action since this is before update trigger
}

You better go through the documentation Triggers and Order of Execution. It will explain you much more things related to this topic.