Trigger for Update #2046
-
I am trying to create something that is similar to that of Facebook's reactions. Reactions Table
Post_reaction Table
Each time a user reacts to a post, it gets added to the reactions table. Similarly, if they update their reaction or remove it, it gets reflected on the table. I intend to set a trigger so that each time the reactions table gets updated, it reflects in the post_reactions table, so that it is easier to get the aggregate when displaying it to the end user. I have set a trigger for INSERT and DELETE that looks something like this
My question is, how do I do handle the UPDATE function? Do I perform a trigger that is something like this?
Or is there a better way? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
I see 3 approaches to solve that:
|
Beta Was this translation helpful? Give feedback.
I see 3 approaches to solve that:
Use a
MATERIALIZED VIEW
to aggregate the data. Then refresh thatCONCURRENTLY
periodically. This means, that the total numbers of reactions might not always be accurate immediately. In the future, incremental view maintenance might be implemented in PG, which would solve that.Use the trigger approach, but aggregate the full
post_reaction
row after each insert/update/delete toreactions
.Use the trigger approach and create the
UPDATE
statement you're using right now via dynamic SQL. In this case you don't need all the IF conditions.