Sub topic 7
Querying information_schema and pg_catalog
This chapter assumes you can connect with psql, run meta-commands such as \dt and \d+, and write basic SQL with joins and filters. You should also know the server, database, schema and object hierarchy from the first chapter.
Meta-commands are convenient, but they only work inside psql. Under the hood, they run ordinary queries against system tables. If you query those tables yourself, you can inspect a database from any client, filter results with WHERE, and feed them into scripts. PostgreSQL gives you two places to look: information_schema and pg_catalog.
Two sources of metadata
Every database contains a set of system tables that describe its own contents. This metadata is called the catalog. PostgreSQL exposes it in two layers.
information_schemais a set of views defined by the SQL standard. The same queries work, with small differences, on MySQL, SQL Server and others.pg_catalogis PostgreSQL's own set of system tables and views. It holds everything the server knows, including PostgreSQL-specific features such as extensions, operator classes, and TOAST tables.
| Aspect | information_schema | pg_catalog |
|---|---|---|
| Portability | Standard, works across SQL databases | PostgreSQL only |
| Coverage | Common objects: tables, columns, constraints, views, routines | Everything, including indexes, extensions, types, and statistics |
| Visibility | Shows only objects you own or have privileges on | Shows all objects, though you may not be able to read their contents |
| Speed | Slower, because views join many catalogs and convert types | Faster, because you read the source tables directly |
| Column names | Long, standard names such as `table_schema` | Short names such as `relname`, `nspname` |
Querying information_schema
The view information_schema.columns has one row per column visible to you. This query lists the columns of public.orders:
SELECT column_name, data_type, is_nullable
FROM information_schema.columns
WHERE table_schema = 'public'
AND table_name = 'orders'
ORDER BY ordinal_position;ordinal_position is the column's order in the table, so the result matches the order shown by \d orders. Always filter by table_schema as well as table_name. Two schemas can contain tables with the same name, and without the schema filter you get a mixed result.
Other useful views include:
information_schema.tables: one row per table and view, withtable_typeset toBASE TABLEorVIEW.information_schema.table_constraintsandkey_column_usage: primary keys, foreign keys and unique constraints.information_schema.routines: functions and procedures.information_schema.views: view definitions.
To list the base tables in all non-system schemas:
SELECT table_schema, table_name
FROM information_schema.tables
WHERE table_type = 'BASE TABLE'
AND table_schema NOT IN ('pg_catalog', 'information_schema')
ORDER BY table_schema, table_name;Visibility limits
information_schema hides objects you have no privileges on. If a table seems to be missing from information_schema.tables but \dt or pg_class shows it, the likely cause is that your role has no privilege on that table. Check your role before concluding that the object does not exist.
Querying pg_catalog
pg_catalog is always on the search path, so you can write pg_class instead of pg_catalog.pg_class. Qualifying the name is still safer in scripts.
The most important catalogs are these:
| Catalog | What a row represents |
|---|---|
| `pg_namespace` | A schema |
| `pg_class` | A relation: table, index, view, sequence, materialized view, and so on |
| `pg_attribute` | A column of a relation |
| `pg_index` | Index details, linked to `pg_class` |
| `pg_proc` | A function or procedure |
| `pg_roles` | A role (a readable view over `pg_authid`) |
| `pg_database` | A database in the cluster |
The catalogs link to each other through object identifiers, or OIDs. An OID is a numeric ID that PostgreSQL assigns to each catalog row. The column pg_class.relnamespace holds the OID of the row in pg_namespace that the relation belongs to, so a join on n.oid = c.relnamespace gives you the schema name.
The relkind column
pg_class holds more than tables, so you filter by relkind:
| relkind | Meaning |
|---|---|
| `r` | Ordinary table |
| `i` | Index |
| `v` | View |
| `m` | Materialized view |
| `S` | Sequence |
| `f` | Foreign table |
| `p` | Partitioned table |
A partitioned table has kind p, not r. A query that filters only on 'r' skips partitioned parent tables. Use relkind IN ('r', 'p') if you want both.
Listing columns with pg_attribute
This is the catalog equivalent of the information_schema.columns query:
SELECT a.attnum,
a.attname AS column_name,
format_type(a.atttypid, a.atttypmod) AS data_type,
NOT a.attnotnull AS is_nullable
FROM pg_attribute a
WHERE a.attrelid = 'public.orders'::regclass
AND a.attnum > 0
AND NOT a.attisdropped
ORDER BY a.attnum;Three details matter here:
'public.orders'::regclassconverts a table name into its OID. It raises an error if the table does not exist, which is useful in scripts.attnum > 0removes system columns such asctidandxmin, which have negative numbers.NOT attisdroppedremoves columns that were dropped withALTER TABLE ... DROP COLUMN. PostgreSQL keeps a placeholder row for them.
format_type turns the internal type OID and modifier into text such as character varying(50) or numeric(10,2).
Seeing what psql runs
You do not have to guess how meta-commands work. Start psql with -E (or run \set ECHO_HIDDEN on) and psql prints the SQL behind each meta-command before the result:
psql -E -d mydbThen run \dt public.*. You will see a query over pg_class and pg_namespace, much like the one in the next section. This is a good way to learn catalog queries and to copy them into scripts.
Finding the largest tables
Size questions need pg_class, because information_schema has no size data. The function pg_total_relation_size(oid) returns the size in bytes of a table plus its indexes and TOAST data. TOAST is PostgreSQL's storage for large values that do not fit in a regular row.
SELECT n.nspname AS schema_name,
c.relname AS table_name,
pg_size_pretty(pg_total_relation_size(c.oid)) AS total_size
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind = 'r'
AND n.nspname NOT IN ('pg_catalog', 'information_schema')
ORDER BY pg_total_relation_size(c.oid) DESC
LIMIT 10;Note that the ORDER BY uses the raw byte count, not the formatted text. Sorting by total_size would sort strings, so 900 kB would come after 10 GB.
Related functions:
pg_relation_size(oid): the table's main data only, without indexes or TOAST.pg_indexes_size(oid): all indexes on the table.pg_database_size('mydb'): the whole database.
Common errors
- Missing schema filter. Without
n.nspname NOT IN (...), system tables fill the results. - Comparing case-sensitive names. Names created with double quotes, such as
"Orders", keep their capital letters. Queryingrelname = 'orders'will not find them. - Casting a missing table to regclass.
'orders'::regclassdepends onsearch_path. Qualify the name with its schema. - Treating
reltuplesas exact.pg_class.reltuplesis an estimate updated byVACUUMandANALYZE. Usecount(*)when you need an exact figure. - Editing catalogs. Never run
UPDATEorDELETEon system tables. Use DDL commands instead.
Exercise
You run SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'; and a table you know exists is missing. \dt run by a superuser shows it. Give a likely cause and a query that would reveal the table to your current role's session without changing privileges.
Show answer
The most likely cause is that your role has no privilege on the table, because informationschema only shows objects the current role can access. Query pgclass instead: SELECT c.relname FROM pgclass c JOIN pgnamespace n ON n.oid = c.relnamespace WHERE n.nspname = 'public' AND c.relkind IN ('r', 'p'); This lists the table regardless of privileges.
Exercise
Write a query that returns the ten largest indexes by size, with schema name, index name and a readable size.
Show answer
SELECT n.nspname AS schemaname, c.relname AS indexname, pgsizepretty(pgrelationsize(c.oid)) AS indexsize FROM pgclass c JOIN pgnamespace n ON n.oid = c.relnamespace WHERE c.relkind = 'i' AND n.nspname NOT IN ('pgcatalog', 'informationschema') ORDER BY pgrelation_size(c.oid) DESC LIMIT 10;