Working with Schemas

1. Creating Schema

CREATE SCHEMA app;
CREATE SCHEMA IF NOT EXISTS reporting AUTHORIZATION analyst;
ClausePurpose
IF NOT EXISTSIdempotent creation
AUTHORIZATION roleSets owner
Embedded objectsCREATE SCHEMA app CREATE TABLE t(...) CREATE VIEW v AS ...

2. Listing Schemas

\dn
\dn+                  -- with ACLs
SELECT schema_name FROM information_schema.schemata;
SELECT nspname FROM pg_namespace WHERE nspname NOT LIKE 'pg_%';
Built-inRole
publicDefault schema
pg_catalogSystem catalogs
information_schemaSQL standard metadata
pg_temp_*Per-session temp objects

3. Setting Schema Owner

ALTER SCHEMA app OWNER TO app_owner;
EffectDetail
PrivilegeOwner can drop/alter/create within schema
Existing objectsNot reowned automatically (use REASSIGN OWNED)

4. Setting Search Path

SET search_path = app, public;            -- session
ALTER ROLE alice SET search_path = app, public;
ALTER DATABASE shop SET search_path = app, public;
TokenMeaning
"$user"Schema matching current role
publicPublic schema
First matchUsed for unqualified references

5. Viewing Current Search Path

SHOW search_path;
SELECT current_schemas(true);    -- includes implicit (pg_catalog)
SELECT current_schema();
FunctionReturns
current_schema()First non-temp schema in path
current_schemas(boolean)Array of effective schemas

6. Creating Schema with Authorization

CREATE SCHEMA AUTHORIZATION alice;        -- schema named 'alice'
CREATE SCHEMA reports AUTHORIZATION analyst;
PatternEffect
AUTHORIZATION onlySchema name = role name
Name + AUTHORIZATIONCustom name, given owner

7. Using Qualified Names

SELECT * FROM app.customers;
SELECT app.full_name(c) FROM app.customers c;
FormMeaning
schema.tableDisambiguates across schemas
db.schema.tableOnly allowed for current DB
"Schema".tableQuote case-sensitive identifiers

8. Renaming Schema

ALTER SCHEMA reports RENAME TO reporting;
RequirementDetail
CallerSchema owner or superuser
Side effectReferences by qualified name break

9. Changing Schema Owner

ALTER SCHEMA app OWNER TO new_owner;
REASSIGN OWNED BY old_owner TO new_owner;  -- all objects
CommandScope
ALTER SCHEMASchema only
REASSIGN OWNEDSchema + all owned tables/funcs
DROP OWNED BYDrop all objects of role

10. Dropping Schema

DROP SCHEMA staging;                -- fails if not empty
DROP SCHEMA IF EXISTS staging;
ModeBehavior
default (RESTRICT)Errors if objects exist
CASCADEDrops dependent objects

11. Dropping Schema Cascade

DROP SCHEMA staging CASCADE;
Warning: CASCADE will silently drop foreign keys, views, sequences, and any object referencing the schema. Inspect dependencies first with \d+ and pg_depend.
Pre-drop CheckQuery
TablesSELECT tablename FROM pg_tables WHERE schemaname='staging';
DependentsSELECT * FROM pg_depend WHERE refobjid='staging'::regnamespace;