0

Whenever user rates a movie such trigger should be called and update the rating of a rated movie. How do I fetch value of movie_id from query insert into ratings values (movie_id, /*etc*/)?

create trigger new_rating after insert on ratings
execute procedure update_movie_rating();

create or replace function update_movie_rating()
returns trigger 
as $new_rating$
begin 
update movies 
set averagerating =
select avg(r.rating)
from ratings r
where r.movie_id = /*movieid fetched from insert query*/
return new;
end;
$new_rating$ language plpgsql;
1

1 Answer 1

1

Assuming field in table "ratings"is called movie_id:

where r.movie_id = NEW.movie_id

You can find a detailed explanation here: https://www.postgresql.org/docs/current/plpgsql-trigger.html

Anyway, you are interested in this specific part:

When a PL/pgSQL function is called as a trigger, several special variables are created automatically in the top-level block. They are:

NEW:

Data type RECORD; variable holding the new database row for INSERT/UPDATE operations in row-level triggers. This variable is null in statement-level triggers and for DELETE operations.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.