4

On PostgreSQL 9.6, how can I do the equivalent of CREATE TRIGGER IF NOT EXISTS? I noticed that in PostgreSQL 14 you can do CREATE OR REPLACE TRIGGER but I'm using 9.6 which doesn't have that.

2
  • CREATE TRIGGER IF NOT EXISTS won't create new trigger version storing old one if the trigger exists rather than CREATE OR REPLACE TRIGGER which creates new trigger version dropping the old one. What do you need in? Commented Jul 12, 2023 at 7:07
  • @Akina I prefer CREATE TRIGGER IF NOT EXISTS if that is possible, but will settle for CREATE OR REPLACE TRIGGER but even that isn't possible. Replacing the trigger is fine, because the new one is exactly the same as the old one. Commented Jul 12, 2023 at 8:52

1 Answer 1

3

Yo can simply run the CREATE TRIGGER statement and ignore the error:

DO
$$BEGIN
   CREATE TRIGGER ...
EXCEPTION
   WHEN duplicate_object THEN
      NULL;
END;$$;

If CREATE OR REPLACE TRIGGER is a solution for you, that's yet another argument for an upgrade. Note that you are running an unsupported version of PostgreSQL, and that's not a smart thing to do if your data are important to you. I can tell from my experience that "it has worked so far, so let's not change anything" is not a good recipe to avoid trouble.

4
  • Even upgrading to PostgreSQL 14 so I can do CREATE OR REPLACE TRIGGER isn't ideal, because it's still not the same as CREATE TRIGGER IF NOT EXISTS. It's still a second-rate solution, because I really don't want to replace the trigger. Commented Jul 12, 2023 at 9:05
  • Well, I gave you the solution. Commented Jul 12, 2023 at 9:29
  • I'll accept your posted solution as the correct one. The comment about upgrading was actually the "second-rate" solution. Commented Jul 12, 2023 at 9:53
  • True. I have reworded the answer. There are no good reasons for running an old version of PostgreSQL. Commented Jul 12, 2023 at 10:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.