Postgresql: Check if Schema Exists?
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?
The following query will tell you whether a schema exists.
SELECT schema_name FROM information_schema.schemata WHERE schema_name = 'name';
If you are a total purist or you want to gain some milisecs. I recommend you to make use of postgres native system catalog. One can avoid then nested loop which is caused by calling pg_catalog anyway...
SELECT EXISTS(SELECT 1 FROM information_schema.schemata
WHERE schema_name = 'name');
If you querying pg_namespace directly:
SELECT EXISTS(SELECT 1 FROM pg_namespace WHERE nspname = 'name');
Planer's work is much simpler:
So your own solution was the best.
Somewhat related and perhaps of interest to others looking for conditional schema creation. I found myself using code like this in some of my creation scripts:
DO $$
BEGIN
IF NOT EXISTS(
SELECT schema_name
FROM information_schema.schemata
WHERE schema_name = 'pgcrypto'
)
THEN
EXECUTE 'CREATE SCHEMA pgcrypto';
END IF;
END
$$;
This can be one of the approaches. Drop the schema first and then create it.
IF EXISTS:
Do not throw an error if the schema does not exist. A notice is issued in this case.
So,
DROP SCHEMA IF EXISTS schema_Name
Create SCHEMA schema_Name