Skip to content

Instantly share code, notes, and snippets.

@CEZERT
Last active September 15, 2022 21:22
Show Gist options
  • Save CEZERT/4005e4e12bf9e2e97aa78753765473b3 to your computer and use it in GitHub Desktop.
Save CEZERT/4005e4e12bf9e2e97aa78753765473b3 to your computer and use it in GitHub Desktop.

exp(url:https://www.postgresqltutorial.com/postgresql-triggers/creating-first-trigger-postgresql/)

CREATE 2 TABLES

CREATE TABLE employee
(emp_id int4,
employee_name varchar(25),
department_id int4,
salary numeric(7,2));

CREATE TABLE emp_salary_history
emp_id int,,
employee_name varchar(25),
salary numeric(7,2)
Changed_on timestamp(6));

CREATE FUNCTION A EXECUTER

CREATE OR REPLACE FUNCTION public.insert_into_salary_history()
 RETURNS TRIGGER
 LANGUAGE plpgsql
AS 
$BODY$
BEGIN
INSERT INTO emp_salary_history(emp_id, employee_name, salary, changed_on) 
values (OLD.emp_id, OLD.employee_name, OLD.salary, now());
return new;
end;
$BODY$
LANGUAGE plpgsql VOLATILE

CREATE TRIGGER THAT WILL LANCE THE FUNCTION

CREATE TRIGGER emp_history_trigger
BEFORE UPDATE OF salary
ON employee FOR EACH ROW
EXECUTE PROCEDURE insert_into_salary_history();

Trigger syntax

CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF} {event [OR ...]}
ON table_name
[FOR [EACH] {ROW | STATEMENT}]
EXECUTE PROCEDURE trigger_function;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment