Updating an existing average with a new value (for DB cache)

Calculating averages can be an expensive operation. Say you have 10 million customer database records and you want to keep track of the average age of your customers. You can either:

  • Recalculate the average everytime it is required, accessing all 10 million database records and summing them up in the process, or;
  • Cache an average and update it every time a new customer is added to the database.

This equation is what you need:

{{a}_{new}}{=}{\frac {nr+x} {n+1}}

Where n is the number of records, a is the current average and r is the new value to be added.