Postgresql: Check if Schema Exists?

前端 未结 10 1550
星月不相逢
星月不相逢 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: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.

提交回复
热议问题