Triggers
This guide will help you in creating and managing triggers on Supabase tables, including how to set up triggers for various events.
Overview
A trigger in Supabase is a database object that automatically executes or "fires" a specified function in response to certain events on a table, such as INSERT, UPDATE, or DELETE operations. Triggers allow you to enforce rules, ensure data consistency, or perform additional actions automatically when specific database events occur.
Significance of Triggers
Triggers are essential for:
- Automating tasks like data logging, auditing, or cascading updates.
- Enforcing business rules by ensuring that certain conditions are met before data is inserted, updated, or deleted.
- Maintaining referential integrity by automatically updating related data in different tables when a change occurs.
- Performing complex validations that might be difficult to enforce through simple constraints.
Creating Triggers in Supabase
How to Create Triggers
Triggers can be created using SQL commands within your Supabase development environment (such as a local PostgreSQL database or Supabase CLI).
-
Create the Trigger Function: First, define the function that will execute when the trigger is fired. A function defines the logic to be executed upon the trigger event.
Example:
For more information on functions refer supabase functions -
Create the Trigger: Once the function is defined, create the trigger that will fire the function on specific table events (e.g., INSERT, UPDATE, DELETE).
Example:
Example of a Trigger for Insertion.
Insertion Trigger
Summary of What Happens
- Every time a new row is inserted into the
profiles
table, the trigger fires after the row is inserted. - The trigger then calls the
log_inserted_user()
function, which:- Logs the newly inserted profile's ID, the type of action (
INSERT
), and the current timestamp in theaudit_log
table. - Returns the newly inserted row to maintain the integrity of the original
INSERT
operation.
- Logs the newly inserted profile's ID, the type of action (
You can create triggers for Updation and deletion of entries on tables.