In this tutorial, we will learn trigger by building auto copy record from source table to destination table.
source_to_trigger
updatesource_to_trigger
to destination_copy
First of all create all the table
CREATE TABLE source_to_trigger (
id uuid DEFAULT uuid_generate_v4(),
title TEXT,
created_at TIMESTAMPTZ DEFAULT NOW(),
CONSTRAINT source_to_trigger_pkey PRIMARY KEY (id)
);
CREATE TABLE destination_copy (
id uuid DEFAULT uuid_generate_v4(),
title TEXT,
created_at TIMESTAMPTZ DEFAULT NOW(),
CONSTRAINT destination_copy_pkey PRIMARY KEY (id)
);
If you got error from uuid
, then you should enable by
CREATE EXTENSION "uuid-ossp";
In PostgreSQL, “Procedure” is one kind of function.
CREATE OR REPLACE FUNCTION copy_record() RETURNS TRIGGER AS
$$
BEGIN
TRUNCATE TABLE destination_copy;
INSERT INTO destination_copy SELECT * FROM source_to_trigger;
RETURN NULL;
END;
$$
LANGUAGE plpgsql;
Some important note here:
NULL
.TRIGGER
in case we want to bind it to TRIGGER
.$$
can have any name in between $
e.g., $copy_record$
or we can leave it like that.CREATE TRIGGER copy_record_trigger_update
AFTER UPDATE ON source_to_trigger
EXECUTE PROCEDURE copy_record();
CREATE TRIGGER copy_record_trigger_insert
AFTER INSERT ON source_to_trigger
EXECUTE PROCEDURE copy_record();
If you have Dbeaver or other client tool, you can see it appear
Test by insert the record into the table
Test by update the record on the source table
Here we go.
Hope this help !
When there is slip in the step you can delete and begin again