Skip to content
Advertisement

Postgres trigger to update counter in another table not working

  • There is users table and places table.

  • The users table has column id(primary key), username, place_count.

  • The places table has column id(primary key), name, user_id (user_id foreign key)

  • Each user can post multiple photos and so I want the column”place_count” to keep the count of user-specific places from places table (eg, user with id 1 having place_count = 150, user with id 2 having place_count = 244 etc etc).

I made use of trigger

Trigger function

Trigger creation

I have inserted some users in users table with initial value of place_count = 0.

PROBLEM : When I update the places with the name and user_id I expect the trigger to increment the place_count by 1 in users table. But no increment is happening in place_count of user table.
What am I doing wrong?

Advertisement

Answer

To answer your question: multiple syntax errors. This should work:

Your original would actually produce error messages.

And your trigger needs to address INSERT instead of UPDATE:

(UPDATE is not covered, yet!)

But (as has been commented) I wouldn’t go there. Keeping count with a trigger is expensive and error prone.

With an index on places (user_id) (like you should have anyway) this query returns the current count very quickly:

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