I have two tables: Purchases(pid, amount), Total_Expense(total_amount) // stores the total $ amount of all purchases.
I want to create a trigger that after a value has been added/deleted/updated to purchases, it will make the total_amount change to the new value. Ex:
| PID | amount |
|---|---|
| 1 | 100 |
| total_amount |
|---|
| 100 |
If you add a new row to purchases:
| PID | amount |
|---|---|
| 1 | 100 |
| 2 | 200 |
then update Total_Expense
| total_amount |
|---|
| 300 |
I've tried:
CREATE OR REPLACE FUNCTION update_sum() RETURNS TRIGGER AS
$$BEGIN
UPDATE total_expense SET total_amount = total_amount + new.amount;
RETURN NULL;
END
$$
LANGUAGE plpgsql;
CREATE TRIGGER updateSum AFTER INSERT OR DELETE OR UPDATE ON purchases
FOR EACH ROW
EXECUTE PROCEDURE update_sum();
This will add the values into purchases but not insert values into total_expense.
I am having a lot of issues with creating my first trigger so any help would be nice. Thanks!