views:

1194

answers:

2

In a MySQL script you can write:

CREATE TABLE IF NOT EXISTS foo ...;

... other stuff ...

and then you can run the script many times without re-creating the table.

How do you do this in PostgreSQL?

A: 

I don't think you can (you can do it with other objects, though - views, I think). You have to drop the table first (if it exists) and then create.

According to this link:

http://blog.thinkopen.co.uk/2007/01/drop-table-if-exists-in-postgresql.html

you can use DROP TABLE IF EXISTS from postgresql 8.2 onwards.

Or this, for older versions of postgresql:

if exists (select 1 from pg_tables where tablename = "thetable")
drop table thetable
davek
Man, this is almost the exact opposite of the needed behavior. This would delete data if there was a table full of it, and not if there wasn't, and then always create a new table. Which is dangerous. I think running a select first might be the only way to go.
Tchalvak
This question though: http://stackoverflow.com/questions/435424/postgresql-how-to-create-table-only-if-it-does-not-already-existHas the solution (i.e. that create table automatically returns false if the table already exists.)
Tchalvak
A: 

There is no CREATE TABLE IF NOT EXISTS... but you can write a simple procedure for that, something like:

CREATE OR REPLACE FUNCTION execute(TEXT) RETURNS VOID AS $$
BEGIN
  EXECUTE $1;
END; $$ LANGUAGE plpgsql;


SELECT 
  execute($$
      CREATE TABLE sch.foo 
      (
        i integer
      )
  $$) 
WHERE 
  NOT exists 
  (
    SELECT * 
    FROM information_schema.tables 
    WHERE table_name = 'foo'
      AND table_schema = 'sch'
  );

That's a little bit weird, but can simply be

Simon