# Is caching in the database wrong?

**URL:** <https://www.ruby-forum.com/t/is-caching-in-the-database-wrong/123468>\
**Category:** Rails\
**Created:** [December 18, 2007, 1:33am UTC](https://www.ruby-forum.com/t/is-caching-in-the-database-wrong/123468 "2007-12-18T01:33:23Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![benjohnson](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/3ec8ea/32.png) [@benjohnson](https://www.ruby-forum.com/u/benjohnson)\
**Post date:** [December 18, 2007, 1:33am UTC](https://www.ruby-forum.com/t/is-caching-in-the-database-wrong/123468/1 "2007-12-18T01:33:23Z")

</div>

For example if I have an order that has many line\_items. The total =  
(sum of line items) + shipping\_cost. Would it be wrong to just add a  
“total” field in the orders table? That basically serves as a cache.  
When an order is created or modified it keeps that value up to date. It  
makes writing queries easier that use total and displaying the total is  
less computational. What do you think? Thanks for your help.

---

<div class="post-metadata">

**Author:** ![benjohnson](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/b/3ec8ea/32.png) [@benjohnson](https://www.ruby-forum.com/u/benjohnson)\
**Post date:** [December 18, 2007, 2:02am UTC](https://www.ruby-forum.com/t/is-caching-in-the-database-wrong/123468/2 "2007-12-18T02:02:25Z")

</div>

> For example if I have an order that has many line\_items. The total =  
> (sum of line items) + shipping\_cost. Would it be wrong to just add a  
> “total” field in the orders table? That basically serves as a cache.  
> When an order is created or modified it keeps that value up to date. It  
> makes writing queries easier that use total and displaying the total is  
> less computational. What do you think? Thanks for your help.

I think it’s fine. As long as you’re careful to make sure this gets  
updated whenver line\_items gets updated.

And that you are aware of the race condition and when it’s really  
important (ie. when you charge the users credit card) that you get the  
_real_ value.

Sure.

I do this all the time for other things like rolling up “views per day”  
into a “total views” column.

-philip
