Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I store a calculate value in my database along with the variables?

Tags:

database

In all the applications I have made where a database is used I typically store the calculated value along with the variables needed to calculate that value. For example, if I have tonnage and cost I would multiply them to calculate the total. I could just recalculate the value every time it is needed, I was just wondering if there was an standard approach. Either way is fine with me, I just want to do what is most common.

If I store the calculate variables it makes my domain classes a bit more complex, but makes my controller logic cleaner, if I don't store the calculated variables it is the other way around.

The calculations would not be extremely frequent, but may be moderately frequent, but math is cheap right?

like image 240
ubiquibacon Avatar asked Dec 16 '11 03:12

ubiquibacon


People also ask

How do you store a value in Access table?

Select a table. Select Click to Add > Calculated Field, and then select a data type. Enter a calculation for the field, and then click OK. Type the expression yourself, or select expression elements, fields, and values to put them into the expression edit field.

Should calculated fields be stored in a table?

Calculated fields belong in queries, not tables. Calculated columns are part of life on a spreadsheet, but do not belong in a database table. Never store a value that is dependent on other fields: it's a basic rule of normalization.

Should I store calculated values in database?

If computers were infinitely fast, then, No, you would never store a value that could be calculated from other columns in the database. Storing calculated values is a violation of database normalization.


1 Answers

The standard approach is not to store this kind of calculated values - it breaks normalization.

There are cases you want to store calculated values, if it takes too long to recalculate, or you are running a data warehouse etc. In your case, you want stick to the normalization rules.

like image 130
勿绮语 Avatar answered Oct 15 '22 13:10

勿绮语