How to Create Trigger Postgresql?

create trigger postgresql

How to create a Postgresql trigger?, in this post we will see how it works, something widely used by developers and database administrators

PostgreSQL for ubuntu

In this practical example we will use the linux operating system with an ubuntu distribution, which is widely used by database administrators, either to work on shared hosting or vps, among the most popular services are Namecheap, GoDaddy, Heroku , DreamHost among others

PostgreSQL 5432

Remember to have postgresql installed on your pc locally or on your remote server using the default port 5432

Postgresql trigger example

The first step would be to create the procedure function, we enter the graphical interface PgAdmin III or 4, or in a terminal with PSQL and add the following code

CREATE OR REPLACE FUNCTION insertstates() RETURNS trigger AS $insertcountrys$

insert into states (state,id_country)
    values('mexico df',new.id_country);
    return new;

$insertcountrys$ LANGUAGE plpgsql;

Now it’s time to create the trigger which will execute the insertstates function after we insert a record into a table called countrys for this example

CREATE TRIGGER insertcountrys
    AFTER INSERT ON countrys
    EXECUTE PROCEDURE insertstates();

PostgreSQL insert into

We proceed to insert a test record

insert into countrys (id_country,country)

After inserting the record in the table called countrys we can verify the result

PostgreSQL select

select * from countrys;

Then we verify that the function has been executed, which would show the result on the screen

select * from states;

With these simple steps we can create trigger in postgresql