postgresqltriggers

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


Solution

  • 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.