13

I'm trying to run this sql which create a new type if is is not existed:

IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'ai') CREATE TYPE ai AS (a text, i int);

I got an error at or near "if", I have trying to find out the answer but its no help. I tried this also but it still not work:

CASE (SELECT 1 FROM pg_type WHERE typname = 'ai') WHEN IS NULL THEN CREATE TYPE ai AS (a text, i int);

error near or at "CASE"

3
  • 1
    There's no IF in SQL (at least in postgres). Commented Jun 18, 2019 at 10:57
  • i updated question with case when Commented Jun 18, 2019 at 11:01
  • This is a duplicate question. Commented Aug 14, 2022 at 9:10

1 Answer 1

14

Your IF syntax is wrong, it misses END IF. Depending on the context, i.e. when you're not already in an PL/pgSQL block (like a function etc.), you need to also use an anonymous DO block. And don't forget to check for the schema too, otherwise you might get false positives if the type already exists in another schema.

DO
$$
BEGIN
  IF NOT EXISTS (SELECT *
                        FROM pg_type typ
                             INNER JOIN pg_namespace nsp
                                        ON nsp.oid = typ.typnamespace
                        WHERE nsp.nspname = current_schema()
                              AND typ.typname = 'ai') THEN
    CREATE TYPE ai
                AS (a text,
                    i integer);
  END IF;
END;
$$
LANGUAGE plpgsql;

(Or, if you're already in an PL/pgSQL block, just everything between IF and END IF; including IF and END IF;.)

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

2 Comments

I include IF and END IF but i still got a syntax error near if
Then you may have something wrong before the IF. What I posted works for me: dbfiddle.uk/…

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.