Reputation: 4956
I'm very new to trigger function. Actually this is the first time I'm using it, and I can't pass over an issue. Here is my code:
CREATE OR REPLACE FUNCTION altitude()
RETURNS trigger AS $$
DECLARE
maxaltimeter DOUBLE PRECISION;
BEGIN
SELECT max(altitude) INTO maxaltimeter FROM waypoints WHERE flight_id = OLD.id;
RETURN NEW;
UPDATE flights SET max_altimeter = NEW.maxaltimeter WHERE id=OLD.id;
END;
$$
LANGUAGE plpgsql VOLATILE
COST 100;
CREATE TRIGGER set_altitude
AFTER UPDATE OF status
ON flights
FOR EACH ROW
EXECUTE PROCEDURE altitude();
When running UPDATE on the 'flights' table (status column) I don't get any results (but no errors too). Any ideas? Thank you.
Upvotes: 0
Views: 3189
Reputation:
You got the statements in the wrong order. The RETURN NEW
will terminate the trigger and thus the update will not be run.
It should be:
SELECT max(altitude) INTO maxaltimeter FROM waypoints WHERE flight_id = OLD.id;
UPDATE flights SET max_altimeter = NEW.maxaltimeter WHERE id=OLD.id;
RETURN NEW;
But I hope you are aware that this is not going to be a scalable solution.
Usually it's better to not store calculated/aggregated values in the database, but to calculate them while you retrieve the data. For convenience you might want to create a view that returns you the max() value for each flight.
The only reason why pre-calculating such a value would be if the retrieval is really expensive and you have to do it very often compared to the updates and the retrieval performance is more important than the update performance.
Upvotes: 2