In Postgresql, how can I do a condition to create a table only if it does not already exist?
Code example appreciated.
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 = [AND schemaname = ];
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.
- 热议问题