12

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

1
  • 1
    it's always a good idea to mention what version of postgres you are using Commented Dec 9, 2010 at 12:13

3 Answers 3

21

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.

Sign up to request clarification or add additional context in comments.

7 Comments

@El Yobo, worth mentioning that this feature was introduced in 8.2
@El Yobo It's hard to be sure how many are still using 8.1 - I think a key factor to consider is that it is the default install on RHEL5 and I suspect that means use is still widespread
Yeah, I had the ... pleasure ... of setting up a RHEL server the other day. I thought Debian stable was behind the curve, but RHEL takes the cake.
this is a great answer for dropping but how do I check if a trigger exists before creating it is really what I am after
@reza: if you always drop it first, you will always be able to create it safely. This safely ensures that it never exists when you try to create it.
|
1
CREATE TRIGGER (NameOfTrigger) AFTER INSERT OR UPDATE ON (NameOfTable)   

DROP TRIGGER IF EXISTS (NameOfTrigger) ON (NameOfTable);

Comments

0

you can replace the existing trigger in postgres while creating the trigger - see the docs

CREATE OR REPLACE TRIGGER YOUR_TRIGGER_NAME ...

This is supported in postgres version 12 and above.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.