I'm fairly new to SQL triggers and I'm struggling whit this:
I have a table that stores data about properties and their prices:
id_property price area price_m2
1 1500 60 25
2 3500 85 41
The clients could change the price of their property often, but the area won't. So I want to create a trigger that updates the price_m2 column when the price column is updated.
I've tried something like that or similar variations:
First create the function
CREATE FUNCTION update_precio_m2() RETURNS TRIGGER
AS
$$
BEGIN
update my_table
set price_m2 = new.price/old.area
where (old.id = new.id);
RETURN new;
end
$$
language plpgsql;
Then create the trigger
CREATE TRIGGER update_price_m2
AFTER UPDATE ON my_table
FOR EACH ROW
WHEN (
old.price IS DISTINCT FROM new.price
)
EXECUTE PROCEDURE update_price_m2();
But when I change the price I got unexpected results, like the price_m2 column change for various id's when I only want to change the value for one id (the one who changed).
Note I know it's an antipattern to store columns whose value depends on the operation between two other columns, but there is a reason for that in this case
Thanks!
where. You should have wrotewhere my_table.id = new.id