Postgresql: Check if Schema Exists?

前端 未结 10 1553
星月不相逢
星月不相逢 2021-02-01 12:24

I need to create, manage and drop schemas on the fly. If I go to create a schema that already exists, I want to (conditionally, via external means) drop and recreate it as speci

相关标签:
10条回答
  • 2021-02-01 12:43

    From http://www.postgresql.org/docs/9.1/static/infoschema-schemata.html (emphasis my own):

    The view schemata contains all schemas in the current database that are owned by a currently enabled role.

    So your original solution/query is more reliable than Peter's, albeit non-standard.

    0 讨论(0)
  • 2021-02-01 12:50

    Use

    SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace WHERE nspowner <> 1 AND nspname = 'schemaname');
    

    If you check https://www.postgresql.org/docs/current/static/infoschema-schemata.html, you see

    The view schemata contains all schemas in the current database that the current user has access to (by way of being the owner or having some privilege).

    This means the query in accepted answer using information_schema.schemata doesn't show schemas that the current user isn't the owner of or doesn't have the USAGE privilege on.

    SELECT 1
    FROM pg_catalog.pg_namespace
    WHERE nspowner <> 1 -- ignore tables made by postgres itself
    AND nspname = 'schemaname';
    

    is more complete and will show all existing schemas that postgres didn't make itself regardless of whether or not you have access to the schema.

    0 讨论(0)
  • 2021-02-01 12:50

    This is valid for the PostgreSQL that will check if the schema if exist and if not then will create it:

    CREATE SCHEMA IF NOT EXISTS tenant;
    
    0 讨论(0)
  • 2021-02-01 12:53

    If you want to create a schema if it doesn't exist you can just execute:

    CREATE SCHEMA IF NOT EXISTS foo
    

    Source: https://www.postgresql.org/docs/current/sql-createschema.html

    0 讨论(0)
提交回复
热议问题