Creating a trigger in PostgreSQL involves two main steps: defining a trigger function and then creating the trigger itself. Here's a basic example to get you started:
Create a Trigger Function: This function will define what happens when the trigger is fired. For example, let's create a function that logs inserts into a table.
CREATE OR REPLACE FUNCTION log_insert() RETURNS trigger AS $$
BEGIN
INSERT INTO log_table (log_message) VALUES ('A new row was inserted');
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
Create the Trigger: This binds the trigger function to a specific table and event. For instance, to create a trigger that fires after an insert on your_table
:
CREATE TRIGGER after_insert_trigger
AFTER INSERT ON your_table
FOR EACH ROW
EXECUTE FUNCTION log_insert();
In this example, every time a new row is inserted into your_table
, a message will be logged into log_table
Feel free to ask if you need more details or have a specific use case in mind!