Working with System Catalogs
1. Understanding System Catalogs
| Catalog | Contents |
|---|---|
| pg_class | Tables, views, indexes, sequences |
| pg_attribute | Columns |
| pg_index | Index metadata |
| pg_constraint | Constraints |
| pg_namespace | Schemas |
| pg_proc | Functions / procedures |
| pg_type | Data types |
| pg_database | Databases |
| pg_roles | Roles (view of pg_authid) |
| pg_settings | GUC parameters |
2. Querying pg_class
SELECT relname, relkind, reltuples, pg_size_pretty(pg_relation_size(oid))
FROM pg_class WHERE relkind IN ('r','p') ORDER BY pg_relation_size(oid) DESC;
3. Querying pg_attribute
SELECT attname, format_type(atttypid, atttypmod), attnotnull
FROM pg_attribute
WHERE attrelid = 'orders'::regclass AND attnum > 0 AND NOT attisdropped
ORDER BY attnum;
4. Querying pg_constraint
SELECT conname, contype, pg_get_constraintdef(oid)
FROM pg_constraint WHERE conrelid = 'orders'::regclass;
5. Querying pg_index
SELECT i.indexrelid::regclass AS index, indisunique, indisprimary,
pg_get_indexdef(indexrelid)
FROM pg_index i WHERE indrelid = 'orders'::regclass;
6. Querying pg_database
SELECT datname, pg_size_pretty(pg_database_size(datname)), datcollate, datctype
FROM pg_database WHERE NOT datistemplate;
7. Querying pg_namespace
SELECT nspname, nspowner::regrole FROM pg_namespace
WHERE nspname NOT LIKE 'pg\_%' ESCAPE '\' AND nspname <> 'information_schema';
8. Querying pg_proc
SELECT p.proname, pg_get_function_identity_arguments(p.oid)
FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace
WHERE n.nspname = 'public' AND p.prokind = 'f';
9. Querying pg_type
SELECT typname, typcategory FROM pg_type WHERE typcategory = 'E'; -- enums
10. Querying pg_roles
SELECT rolname, rolcanlogin, rolconnlimit, rolvaliduntil FROM pg_roles;
11. Querying pg_tables
SELECT schemaname, tablename, tableowner FROM pg_tables WHERE schemaname = 'public';
12. Querying pg_indexes
SELECT tablename, indexname, indexdef FROM pg_indexes WHERE schemaname='public';
13. Using information_schema
SELECT table_schema, table_name, column_name, data_type
FROM information_schema.columns WHERE table_schema = 'public';
Note: ANSI-portable but slower than pg_catalog. Prefer pg_catalog for PG-specific tooling.
14. Querying pg_settings
SELECT name, setting, unit, source, sourcefile, pending_restart
FROM pg_settings WHERE name LIKE '%memory%' OR name LIKE '%wal%';