55

In Postgresql, how can I do a condition to create a table only if it does not already exist?

Code example appreciated.

1
  • 1
    What do you want to have happen if your table definition doesn't match the existing one? Error, modify the table, do nothing? Some context would help.
    – Kev
    Jan 12, 2009 at 14:05

10 Answers 10

99

I'm not sure when it was added, but for the sake of completeness I'd like to point out that in version 9.1 (maybe before) IF NOT EXISTS can be used. IF NOT EXISTS will only create the table if it doesn't exist already.

Example:

CREATE TABLE IF NOT EXISTS users.vip
(
  id integer
)

This will create a table named vip in the schema users if the table doesn't exist.

Source

1
24
create or replace function update_the_db() returns void as
$$
begin

    if not exists(select * from information_schema.tables 
        where 
            table_catalog = CURRENT_CATALOG and table_schema = CURRENT_SCHEMA
            and table_name = 'your_table_name_here') then

        create table your_table_name_here
        (
            the_id int not null,
            name text
        );

    end if;

end;
$$
language 'plpgsql';

select update_the_db();
drop function update_the_db();
2
  • 1
    This doesn't take the current schema into account, i.e. it'll check whether the table exists in any schema and not create it in the current one if it does.
    – BuschnicK
    Nov 15, 2010 at 13:12
  • 1
    I posted a very similar, but somewhat simpler version of this to a related question. Found this one just now. Oct 23, 2011 at 4:15
16

Just create the table and don't worry about whether it exists. If it doesn't exist it will be created; if it does exist the table won't be modified. You can always check the return value of your SQL query to see whether the table existed or not when you executed the create statement.

2
  • 6
    Most of the times you don't have to worry indeed.When the creation happens inside a transaction as it will cause the transaction to be aborted.
    – diciu
    Aug 25, 2011 at 16:49
  • 25
    Personally, I think this type of answer / thinking encourages poor practices. If I expected that the table might exist, it's a must to test for that, not check for an error condition. Perhaps in 2011, the paradigm works differently? Right now, when one tries to create a table which already exists, an error is created by the dbms.
    – Jeff Maass
    Sep 14, 2011 at 15:41
12

I think to check the pg_class table perhaps help you, something like that:

SELECT COUNT (relname) as a FROM pg_class WHERE relname = 'mytable'

if a = 0 then (CREATE IT)

Regards.

7

This is an old question. I'm only bringing back to suggest another answer. Note: other better answers already exist, this is just for educational purposes.

The easiest way is to do what others have said; perform the CREATE TABLE if you want to keep the existing data, or perform a DROP IF EXISTS and then a CREATE TABLE, if you want a freshly created table.

Another alternative is to query the system table for its existence and proceed from there.

SELECT true FROM pg_tables WHERE tablename = <table> [AND schemaname = <schema>];

In use:

-- schema independent:
SELECT true FROM pg_tables WHERE tablename = 'foo';

-- schema dependent:
SELECT true FROM pg_tables WHERE tablename = 'foo' AND schemaname = 'bar';

If it matches you'll have a true value, otherwise it should return an empty dataset. You can use that value to determine if you need to perform a CREATE TABLE.

1
  • 1
    Worth noting that if you use AND schemaname = <schema> things like temporary tables will exist, but will be put in a different schema... Apr 17, 2013 at 15:00
3

The best answer has been given by Skalli if you're running Postgresql 9.1+.

If like me you need to do that with Postgresql 8.4, you can use a function with a 'duplicate_table' exception catch.

This will ignore the generated error when the table exists and keep generating other errors.

Here is an example working on Postgresql 8.4.10 :

CREATE FUNCTION create_table() RETURNS VOID AS
$$
BEGIN
    CREATE TABLE my_table_name(my_column INT);
EXCEPTION WHEN duplicate_table THEN
    -- Do nothing
END;
$$
LANGUAGE plpgsql;
2

What I used to check whether or not a table exists (Java & PostgreSQL) prior to creating it. I hope this helps someone. The create table portion is not implemented here, just the check to see if a table already exists. Pass in a connection to the database and the tableName and it should return whether or not the table exists.

public boolean SQLTableExists(Connection connection, String tableName) {
    boolean exists = false;

    try {
        Statement stmt = connection.createStatement();
        String sqlText = "SELECT tables.table_name FROM information_schema.tables WHERE table_name = '" + tableName + "'";    
        ResultSet rs = stmt.executeQuery(sqlText);

        if (rs != null) {
            while (rs.next()) {
                if (rs.getString(1).equalsIgnoreCase(tableName)) {
                    System.out.println("Table: " + tableName + " already exists!");
                    exists = true;
                } else { 
                    System.out.println("Table: " + tableName + " does not appear to exist.");
                    exists = false;
                }

            }
        }

    } catch (SQLException sqlex) {
        sqlex.printStackTrace();
    }
    return exists;
}
1
  • 2
    You might want to include the schema_name in the query to cate for the same table in different schemas.
    – user330315
    Apr 27, 2012 at 7:43
2

The easiest answer is :

catch{

#create table here

}

This creates a table if not exists and produces an error if exists. And the error is caught.

1

http://www.postgresql.org/docs/8.2/static/sql-droptable.html

DROP TABLE [ IF EXISTS ] name [, ...] [ CASCADE | RESTRICT ]
1
  • 5
    He doesn't want to drop the table if it exists. He wants to create it if it doesn't exist. Dec 16, 2011 at 18:16
0

Try running a query on the table. If it throws an exception then catch the exception and create a new table.

try {
    int a =  db.queryForInt("SELECT COUNT(*) FROM USERS;");
}
catch (Exception e) {
    System.out.print(e.toString());
    db.update("CREATE TABLE USERS (" +
                "id SERIAL," +
                "PRIMARY KEY(id)," +
                "name varchar(30) NOT NULL," +
                "email varchar(30) NOT NULL," +
                "username varchar(30) NOT NULL," +
                "password varchar(30) NOT NULL" +
                ");");
}
return db;

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

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