Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

postgres trigger creation

How do I only create a trigger if it does not exist?

When I do create or replace, I get a syntax error so I am looking for a way to test for the existence of a trigger.

I can always select * from pg_trigger, but I am sure there is a more suitable way.

Thanks

like image 795
reza Avatar asked Dec 09 '10 01:12

reza


People also ask

How do I create a trigger in PostgreSQL?

PL/pgSQL can be used to define trigger functions on data changes or database events. A trigger function is created with the CREATE FUNCTION command, declaring it as a function with no arguments and a return type of trigger (for data change triggers) or event_trigger (for database event triggers).

How trigger is created?

A trigger is a special type of stored procedure that automatically runs when an event occurs in the database server. DML triggers run when a user tries to modify data through a data manipulation language (DML) event. DML events are INSERT, UPDATE, or DELETE statements on a table or view.

What is a Postgres trigger?

A PostgreSQL trigger is a function called automatically whenever an event such as an insert, update, or deletion occurs. A PostgreSQL trigger can be defined to fire in the following cases: Before attempting any operation on a row (before constraints are checked and the INSERT, UPDATE or DELETE is attempted).


2 Answers

Postgres can conditionally drop a trigger - see the docs. Do this before creating the trigger, then it will always work.

DROP TRIGGER IF EXISTS mytrigger ON mytable;

As Jack points out in the comments, this feature has only been available since 8.2; this has been out for more than four years though, so it should be available in your version.

like image 57
El Yobo Avatar answered Oct 07 '22 11:10

El Yobo


CREATE TRIGGER (NameOfTrigger) AFTER INSERT OR UPDATE ON (NameOfTable)   

DROP TRIGGER IF EXISTS (NameOfTrigger) ON (NameOfTable);
like image 34
bedjaoui djounaydi Avatar answered Oct 07 '22 12:10

bedjaoui djounaydi