Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

185
Views
Create a SQL trigger

Helloo !

So I am a bit noob in SQL and I'm trying to create a trigger to get the average score of a movie.

I got three tables, users, relation and movies :

  • In users there is an id, name, pwd, etc.

  • In movies there is an id, title, director and averageScore (that I
    want to update)

  • In relation there is the user ID called idUser, the movie ID called
    idMovie and the score

So each time that a user adds a movie, there is a new relation row with the id of the User, the id of the movie and the score that the user gives

I want to make an average of the score for each movie each time that a new relation is created

So for that I create this trigger

CREATE TRIGGER Average
AFTER INSERT ON relation
FOR EACH ROW
    UPDATE movies
    SET averageScore = (SELECT AVG(score) FROM relation WHERE movies.id = relation.idMovie)

But when a new relation is created, the averageScore of movies doesn't change, and I can't find the problem. Please help me ! x)

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

The trigger was a good start, but you missed some points.

movies.id is not part of relations the new values you adress with NEW.idMovie

The last is you have to specify the row you want to update.

CREATE TABLE movies(id int, averageScore DECIMAL(4,2));
CREATE TABLE relation(iduser INT, idMovie INT,score DECIMAL(4,2));
INSERT INTO movies VALUES (1,0),(2,0);
CREATE TRIGGER Average
AFTER INSERT ON relation
FOR EACH ROW
    UPDATE movies
    SET averageScore = (SELECT AVG(score) FROM relation WHERE idMovie  = NEW.idMovie)
WHERE movies.id = NEW.idMovie
INSERT INTO relation VALUES (1,1,0.5),(2,1,0.7),(3,1,0.2)
SELECT * FROM movies;
id | averageScore
-: | -----------:
 1 |         0.47
 2 |         0.00

db<>fiddle here

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!