Postgresql Create Trigger Before Deleting A Row

Nano picture Nano · Jul 8, 2016 · Viewed 15.6k times · Source

so i have these two tables:

 -- Table user
 columns: id,name,surname, password,token,earnedmoney


 -- Table addlisting
 columns: id, user_fk,price,date_added

Here is my problem: I would like to create a trigger so that when I delete a listing from the table addlisting, the price of the listing gets added to the column "earnedmoney" which is in the table user.

Could somebody help me? Thank you!

Answer

Laurenz Albe picture Laurenz Albe · Jul 8, 2016
CREATE OR REPLACE FUNCTION add_money() RETURNS trigger AS
$$BEGIN
   UPDATE "user" SET earnedmoney = earnedmoney + OLD.price
      WHERE id = OLD.user_fk;
   RETURN OLD;
END;$$ LANGUAGE plpgsql;

CREATE TRIGGER add_money
   BEFORE DELETE ON addlisting FOR EACH ROW
   EXECUTE PROCEDURE add_money();

It could also be an AFTER trigger, that would make no difference.