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
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.
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.
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;
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