Account Trigger find Ultimate Parent Account

Your solution will really depend on how many levels you need to be able to support.

For instance, if you can rely on only going 10 levels deep then you can just use a formula field as per Adrian's answer to Need a custom field Grand parent Account which has highest level of account hierarchy.


Another alternative is to use a text field to maintain the hierarchy. It would essentially store the path from the current node to the ultimate parent.

E.g. Using your identifiers. In reality you would use the 18 character record IDs and a suitable delimiter.

  • For B4 it would be A1|B1|B2
  • For B3 A1|B1

Then if there is ever a modification to a non-leaf nodes parent you can perform a SOQL search to find all the affected nodes that need to be updated. Potentially doing so via a batch process to correct their parent relationship.