I’ve created a SQL table with a field X and a field DATE. I would like to compute the sum of X where DATE < d. I’ve two possibilities :
- Create a new field, “sum of X”, which represents the sum of X when date < date[field]
- Compute the sum of X “manually”, with a SQL request
Is there a method which is always superior ? Or, if not, I assume that it depends on the table size. What is the approximate size that equalizes the two methods ?
Thank you very much.
No. But in general, stick with the simplest solution until you find it doesn’t work any more. The simplest solution in this case is to calculate the derived field each time you need it.
Yes. And the number of insertions vs. number of reads. And whether dates are monotonically increasing or not. And the space (memory/disk) vs. time (processing power) tradeoff of your system and its requirements. And probably a good number of other things too.
How long is a piece of string? Too many other variables to answer that.
To repeat: stick with simple until forced to do otherwise. Maintaining cached values introduces complexity and corner cases: what are your transactional boundaries? What happens if you add a new row? That presumably triggers a subsequent transaction to detect and update the affected rows. What happens if you then roll back the original transaction?
That’s a lot more logic. With much more potential to go wrong. Stick with YAGNI until you find you do.
hth.