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. <!–more–> 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.

Related posts

Fixing Parse Server Request Entity Too Large Error with Node.js and JavaScript: Troubleshooting Permission Errors

Taking playlist randomisation into my own hands – using Javascript to improve Spotify’s Broken Shuffle

Sequelize throws SequelizeDatabaseError when using JavaScript Dates

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Read More