This is a problem of space vs time, I guess.
Consider a online quizzing application. In the browse-quizzes, with every quiz, I wish to show how many questions it has.
- If a quiz has 10 questions, I may show it as “10 questions”, or “medium duration quiz”.
- If a quiz has 5 questions, I may show it as “5 questions”, or “short duration quiz”.
In the Quiz table, I don’t have a column for storing the number of questions.
To find that number of questions, I can do
SELECT COUNT(question_id)
FROM Quiz
NATURAL JOIN Quiz_data
WHERE quiz_id = '$quiz_id'
Note that Quiz_data is a cross table of Quiz and Question_bank (i.e. it stores PKs of both the 2 table).
Note that if I store the *number_of_question* in Quiz, questions may be added/subtracted from Quiz. So apart from delete and insert, one needs to update as well.
Question: should I compute each time, or store the value in the Quiz table? The post title says the same question in general sense.
You need to know
(1) how often your data changes, and
(2) how much effort it takes to determine that number.
As a general recommendation, I would look at:
If the data changes only very rarely -> you should calculate and then store that value.
If the cost of determining that number is very high -> try to calculate once, store and reuse.
On the other hand, if having an accurate count is crucial -> determine it as needed.
This is not a clear-cut yes-or-no decision – it really depends on your data, your requirements, and how costly it is to calculate such a number/count.