Create Trigger

PostreSQL tutorial – Create trigger

Create postgresql trigger

Create Trigger function syntax. Example: before, after, insert, delete, update.

Syntax

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

Example – Create postgresql trigger function

CREATE FUNCTION trg_customers() 
RETURNS trigger AS $$
BEGIN
 IF NEW.first_name IS NULL THEN
  RAISE EXCEPTION 'First_name cannot be null';
 END IF;
 IF NEW.last_name IS NULL THEN
  RAISE EXCEPTION 'Last_name cannot be null';
 END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;

Example – Create postgresql trigger

CREATE TRIGGER customers_trigger 
BEFORE INSERT OR UPDATE ON customers
FOR EACH ROW 
EXECUTE PROCEDURE trg_customers();

Alter / Disable trigger |
Drop trigger