Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql Create Trigger Before Deleting A Row

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!

like image 438
Nano Avatar asked Jul 08 '16 14:07

Nano


People also ask

What is a before delete trigger?

Description. A BEFORE DELETE Trigger means that Oracle will fire this trigger before the DELETE operation is executed.

How do I delete a specific row in PostgreSQL?

First, specify the table from which you want to delete data in the DELETE FROM clause. Second, specify which rows to delete by using the condition in the WHERE clause. The WHERE clause is optional. However, if you omit it, the DELETE statement will delete all rows in the table.

Can we create trigger in PostgreSQL?

Introduction to PostgreSQL CREATE TRIGGER statement First, specify the name of the trigger after the TRIGGER keywords. Second, specify the timing that cause the trigger to fire. It can be BEFORE or AFTER an event occurs. Third, specify the event that invokes the trigger.


1 Answers

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.

like image 171
Laurenz Albe Avatar answered Sep 28 '22 03:09

Laurenz Albe