Postgresql: Check if Schema Exists?

2020-05-19 03:38发布

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 specified. How can I check for the existence of said schema on my Postgres 9 server?

Currently, I'm doing this:

select exists (select * from pg_catalog.pg_namespace where nspname = 'schemaname');

but I feel like there's probably another way... is this the "proper" way to query Postgres for the existence of a particular schema?

9条回答
唯我独甜
2楼-- · 2020-05-19 04:19

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.

查看更多
Bombasti
3楼-- · 2020-05-19 04:19

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.

查看更多
Emotional °昔
4楼-- · 2020-05-19 04:23

This one worked for me (Postgres 9.3):

Select exists (SELECT 1 FROM information_schema.schemata where catalog_name = 'My_BD_with_UpperCase_characters_in_its_Name')
查看更多
登录 后发表回答