Skip to content
Advertisement

PostgreSQL: Create table if not exists AS

I’m using PostgreSQL and am an SQL beginner. I’m trying to create a table from a query, and if I run:

it works just fine. But then if I add ‘if not exists’ and run:

using exactly the same query, I get:

Is there any way to do this?

Advertisement

Answer

CREATE TABLE AS is considered a separate statement from a normal CREATE TABLE, and until Postgres version 9.5 (see changelog entry) didn’t support an IF NOT EXISTS clause. (Be sure to look at the correct version of the manual for the version you are using.)

Although not quite as flexible, the CREATE TABLE ... LIKE syntax might be an alternative in some situations; rather than taking its structure (and content) from a SELECT statement, it copies the structure of another table or view.

Consequently, you could write something like this (untested); the final insert is a rather messy way of doing nothing if the table is already populated:

Alternatively, if you want to discard previous data (e.g. an abandoned temporary table), you could conditionally drop the old table, and unconditionally create the new one:

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement