Backendintermediate

Database Trigger

A function that runs automatically when a specific database event happens, like inserting, updating, or deleting a row.

Detailed Explanation

A database trigger is a function that runs automatically when a specific event happens in your database — like an INSERT, UPDATE, or DELETE on a table.

Triggers are powerful because they let you automate backend logic without writing any frontend code. For example, in Threadly's notifications system, a trigger fires every time a comment is inserted. It automatically creates a notification for the post author — no API call needed.

How Triggers Work

A trigger has two parts:

  1. The trigger function — The SQL code that runs (e.g., "create a notification for the post author")
  2. The trigger itself — The rule that says WHEN to run it (e.g., "after an INSERT on the comments table")

Common Use Cases

  • Auto-creating notifications when something happens
  • Updating a "last_modified" timestamp automatically
  • Maintaining count fields (like comment_count on a posts table)
  • Enforcing business rules that RLS policies can't handle

Triggers run inside the database, so they're fast and reliable. They use Supabase's service role to bypass RLS when needed (like creating a notification for another user).

Related Concepts

Triggers work alongside migrations (you create them via SQL), foreign keys (triggers often reference related tables), and RLS policies (triggers can bypass RLS using the service role).

Ready to Build Something Real?

We give you the skills to build, deploy, and own a full product. Professional stack, AI co-pilot, no coding background required.