© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
SupabaseS
Supabase•3y ago•
5 replies
apost

What is the proper way to update a value after update or insert?

Hello everyone! So I have 2 tables. Table 1 is Profiles and table 2 is Videos. Videos table has a foreign key to the profiles table based on the user_id. On the profiles table I have a column which is called avg_views which basically should be the avarage views of that profile based on the views column on the videos table.

So I have a trigger
-- Create a trigger function
CREATE OR REPLACE FUNCTION profile_update_avg_views_30d()
RETURNS TRIGGER AS $$
BEGIN
  UPDATE profiles
  SET avg_views_30d = (
    SELECT AVG(views)
    FROM videos
    WHERE profile = NEW.user_id
      AND posting_date >= CURRENT_DATE - INTERVAL '30 days'
  )
  WHERE user_id = NEW.user_id; 

  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

-- Create a trigger that fires after every update or insert on the videos table
CREATE TRIGGER profile_update_avg_views_30d_trigger
AFTER INSERT OR UPDATE ON profiles
FOR EACH ROW
EXECUTE FUNCTION profile_update_avg_views_30d();
-- Create a trigger function
CREATE OR REPLACE FUNCTION profile_update_avg_views_30d()
RETURNS TRIGGER AS $$
BEGIN
  UPDATE profiles
  SET avg_views_30d = (
    SELECT AVG(views)
    FROM videos
    WHERE profile = NEW.user_id
      AND posting_date >= CURRENT_DATE - INTERVAL '30 days'
  )
  WHERE user_id = NEW.user_id; 

  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

-- Create a trigger that fires after every update or insert on the videos table
CREATE TRIGGER profile_update_avg_views_30d_trigger
AFTER INSERT OR UPDATE ON profiles
FOR EACH ROW
EXECUTE FUNCTION profile_update_avg_views_30d();

But it seems to cause statement_timeout errors.

I have many more queries like the one above that update different columns. My question is: is this properly written? How can I do this in a better and optimal way?

Thanks in advance!
Supabase banner
SupabaseJoin
Supabase gives you the tools, documentation, and community that makes managing databases, authentication, and backend infrastructure a lot less overwhelming.
45,816Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

What is the proper way to handle supabase directory being a few paths deep into my project?
SupabaseSSupabase / help-and-questions
5mo ago
what is default value of $PGPASSWORD and how to set a value ?
SupabaseSSupabase / help-and-questions
4y ago
What is the "right way" to use URL Configuration? Or auth in localhost?
SupabaseSSupabase / help-and-questions
3y ago
Proper way to the authorize the user in an Inngest function?
SupabaseSSupabase / help-and-questions
6mo ago