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?
In a MySQL script you can write:
... other stuff ... and then you can run the script many times without re-creating the table. How do you do this in PostgreSQL? |
|||||
|
This feature has been implemented in Postgres 9.1:
For older versions, here is a function to work around it:
Call:
If the user does not have the necessary privileges to create the table you might want to use |
|||||||||||||
|
Try this :
|
||||
I created a generic solution out of the existing answers which can be reused for any table:
Usage:
It could be simplified further to take just one parameter if one would extract the table name out of the query parameter. Also I left out the schemas. Feel free to extend my solution if you know how to do that - I'm not that deep into plpgsql yet (this is the first time I'm dealing with it). |
|||
|
This solution is somewhat similar to the answer by Erwin Brandstetter, but uses only the sql language. Not all PostgreSQL installations has the plpqsql language by default, this means you may have to call Adding the plpgsql may not be issue if you are running your script locally, however, if the script is used to set up schema at a customer it may not be desirable to leave changes like this in the customers database. This solution is inspired by a post by Andreas Scherbaum.
|
||||
|
There is no CREATE TABLE IF NOT EXISTS... but you can write a simple procedure for that, something like:
That's a little bit weird, but can simply be |
|||
|