Quantcast
Channel: Question and Answer » postgresql
Viewing all articles
Browse latest Browse all 1138

Is there a way to automatically set triggers to update a field that is computed as an aggregation of other fields?

$
0
0

Let’s say that I have these tables: user, task, and submission. A user can create a submission which will be scored by the system, which will assign a value to submission.score.

Now, everytime a submission.score gets updated, I want to run an UPDATE query to update the user.total_score field, which is basically a SUM() over all submission.score pertaining to this user.

I know I can do this easily with a SQL trigger. However, sometimes the SUM() is not so simple. It may involve multiple fields over many different tables. Let’s say that I have not one, but many types of task: quiz_task, test_task, problem_task, and so on. Every type of task is different (and the user needs to do different things to solve them), and they have a different weight field. The score of a submission now needs to be factored by the weight of the task. I now need to add several triggers which all update the same user.total_score field (which I assume to be the sum of scores from all types of tasks) whenever a submission is re-evaluated (for any reason) or a task weight is changed.

My question is: is there a system, maybe a SQL construct (or something NoSQL?) that allows me to just declare a “computed field” and automatically add the needed triggers?

In theory, I think it’s doable: the system parses the query as a tree (storing intermediate values in the vertices) and everytime a vertex is updated, the system recomputes that subtree and “bubbles up”, updating all the intermediate values and (at the end) the “computed field”.

(In my user.total_score example, the tree would just be a root vertex connected to as many leaves as there are types of tasks)


Viewing all articles
Browse latest Browse all 1138

Trending Articles