List schemas
Schemas are the namespace layer of a database, and in multi-tenant designs one tenant can equal one schema. This query lists all of them with their owners.
The task
You are on an unfamiliar database and need to see how it is partitioned into namespaces and who owns each one, before creating or granting anything.
The snippet
Written for PostgreSQL. Versions for SQL Server and MySQL are under Variations.
SELECT schema_name, schema_owner
FROM information_schema.schemata
ORDER BY schema_name;
Как это работает
information_schema.schemata lists the namespaces of the current database, including pg_catalog, information_schema and pg_toast; filter those out for user schemas only. On PostgreSQL it shows only schemas the current user owns or holds a privilege on, so a superuser and an application role can get different lists. pg_namespace has every schema regardless, plus the nspacl column with its access list.
Variations
SQL Server
SQL ServerSELECT s.name AS schema_name,
dp.name AS owner_name
FROM sys.schemas s
JOIN sys.database_principals dp ON dp.principal_id = s.principal_id
ORDER BY s.name;
MySQL
MySQLSELECT schema_name, default_character_set_name
FROM information_schema.schemata;
-- a schema and a database are the same thing in MySQL;
-- SHOW DATABASES gives the same list. There is no owner.
PostgreSQL: with sizes per schema
PostgreSQLSELECT n.nspname AS schema_name,
pg_size_pretty(sum(pg_total_relation_size(c.oid))) AS total_size
FROM pg_namespace n
JOIN pg_class c ON c.relnamespace = n.oid AND c.relkind = 'r'
WHERE n.nspname NOT IN ('pg_catalog', 'information_schema')
GROUP BY n.nspname
ORDER BY sum(pg_total_relation_size(c.oid)) DESC;
Questions that come up
What is the search_path doing to my queries?
On PostgreSQL, unqualified table names resolve through the search_path setting, which defaults to "$user", public. If you get 'relation does not exist' for a table you can list here, it lives in a schema outside the session's search_path. Check with SHOW search_path.
Keep reading
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.