Skip to content
Advertisement

Create trigger to automatically update column with subquery

In my application, I have a couple of tables, lessons and votes. Here’s what they look like:

Lessons

Votes

Whenever a row in votes is inserted, updated or deleted, I’d like to update the votes_total column of the related lesson using a subquery. Here’s what I’ve tried:

However, when I try to run this in a migration, I get the following error:

Advertisement

Answer

Hi your function must return a trigger. You can’t use new in a trigger on delete. You have to create at least 2 triggers calling the same function and use TG_OP to know if the function is triggered by insert, update or delete.

Then in a case or if statement you can use new or old to get the id’s value.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement