Postgresql: how to create table only if it does not already exist?

后端 未结 10 1107
不思量自难忘°
不思量自难忘° 2021-01-31 08:04

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

Code example appreciated.

10条回答
  •  误落风尘
    2021-01-31 08:19

    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.

    提交回复
    热议问题