-2

This is the way to create a new table in PostgreSQL,

CREATE TABLE foo (
    foo_id  int   PRIMARY KEY,
    bar     text,
);

How do I do this if it needs to check if the table already exists and to proceed with the CREATE only if one is not found?

  • 2
    I've cleaned up the question a lot in order to keep it on topic and useful for future visitors ultimately the cli only runs the command and the fact that you're using the command line and windows has nothing to do with SQL syntax you're requesting. – Evan Carroll Jun 17 '18 at 19:37
7

It needs to check if the table already exists and create only if not found?

There is no standards-compliant method at all, but PostgreSQL 9.1+ supports a common extension with the IF NOT EXISTS clause,

CREATE TABLE IF NOT EXISTS foo (
  foo_id int PRIMARY KEY
);

If the table (foo in this case) doesn't exist, you'll get only a NOTICE (not an ERROR)

NOTICE: relation "foo" already exists, skipping

Note: while the DDL IF NOT EXISTS syntax is non-standard, other databases like MySQL may also support it, and SQL Server's transact SQL supports a variant of it IF NOT EXISTS (query) ... DDL ... GO

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.