In Postgresql, how can I do a condition to create a table only if it does not already exist?
Code example appreciated.
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;
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.
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;
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