PostgreSQL Create Trigger

PostgreSQL Create Trigger

The PostgreSQL CREATE TRIGGER is used to create a trigger in a PostgreSQL database.

Create Trigger syntax

CREATE TRIGGER name
{ BEFORE | AFTER | INSTEAD OF } 
    ON table_name
    [FOR [EACH] {ROW | STATEMENT}]
    EXECUTE PROCEDURE function_name(arguments);

Create Trigger example

Step 1 – Create postgresql trigger function

CREATE FUNCTION f_goods() 
RETURNS trigger AS $$
BEGIN
 IF NEW.name IS NULL THEN
  RAISE EXCEPTION 'Insert name';
 END IF;
 IF NEW.good_type IS NULL THEN
  RAISE EXCEPTION 'Insert good_type';
 END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;

Step 2 – Create postgresql trigger

CREATE TRIGGER trigger_goods
BEFORE INSERT OR UPDATE ON goods
FOR EACH ROW 
EXECUTE PROCEDURE f_goods();