Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgresql: Check if Schema Exists?

Tags:

sql

postgresql

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?

like image 244
Chris Cashwell Avatar asked Aug 10 '11 19:08

Chris Cashwell


People also ask

How do I find the default schema in PostgreSQL?

In PostgreSQL, by default, every database owns a default Schema named public. If you do not mention schema_name while creating or accessing the object then PostgreSQL will consider the schema_name as public. To get the current schema inside a database. SELECT current_schema();

What is PostgreSQL schema?

In PostgreSQL, schema is a named collection of tables, views, functions, constraints, indexes, sequences etc. PostgreSQL supports having multiple schemas in a single database there by letting you namespace different features into different schemas.


1 Answers

The following query will tell you whether a schema exists.

SELECT schema_name FROM information_schema.schemata WHERE schema_name = 'name'; 
like image 192
Peter Eisentraut Avatar answered Sep 18 '22 13:09

Peter Eisentraut