title: How can I optimize this: Many Postgres triggers calling the same function within a transaction
body: <p>I have a cached field in one of my database tables that get's updated based on many different tables and the state of fields in those tables.</p>
  
  <p>Each of those tables calls the same function via a trigger:  updateCachedField(basetable_id INTEGER).  The updateCachedField function queries all these other tables and calculates the new cached value for the base table.  The updateCachedField function is complicated and very cost heavy.</p>
  
  <p>During a single transaction it's possible for many of the tables that affect the cached field to be changed.  So during a single transaction, the updateCachedField function may get called 50 times... but with only 5 different basetable_id's.</p>
  
  <p>Is there a way to optimize this so that the updateCachedField function only gets called 5 times instead of the 50+?</p>