I’m building a simple e-commerce website with order confirmation and creation.
Should I calculate the total order value, and insert it into the database, or should I calculate it every time I read or do something with the order?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Best practices in database land means normalised data, and storing values that can be calculated violates that.
You should generally never store things that you can calculate unless you’re absolutely certain that there won’t be a discrepancy between the two values.
Sometimes, there are justifications (usually performance related) to storing values that can be otherwise calculated but the performance gains have to be both significant and necessary, and the possibility of inconsistency either removed or planned for.
You can remove the possibility with things like triggers or materialised views, and you can plan for them by changing business logic to detect and fix problems, or by other means.
But usually, the performance gains aren’t worth the extra effort of mitigating the potential problems. After all, how many orders do you see with millions of individual items on them?
Other than the US DoD, of course, where the Bill Of Materials for an aircraft carrier lists every single nut and bolt used to build it 🙂