Database Metadata: information_schema and the System Catalogs
How to query a database about itself: listing tables and columns with the standard information_schema, finding constraints and foreign keys, PostgreSQL's system catalogs for sizes and indexes, auditing a schema, generating SQL from metadata, comments, and the equivalents in other databases.
kvi5hnuCode Sprout team member8 min readOn this page
A database describes itself in tables. The names of your tables, their columns and types, constraints, indexes, views, users and permissions are all stored as rows in system tables, and you can query them with ordinary SELECT statements. This metadata, data about the data, is what database tools, IDEs, ORMs and migration tools read to show you a schema.
Knowing how to query it lets you answer questions such as "which tables have a customer_id column?", "which foreign keys have no index?" and "how big is each table?" in seconds, and even generate SQL from the answers.

There are two layers:
information_schema: standard views describing tables, columns and constraints. Because they're standardised, one metadata query can often run unchanged on PostgreSQL, MySQL and SQL Server. Use it for portable scripts.- System catalogs: each database's own tables, such as PostgreSQL's
pg_classandpg_constraint, SQL Server'ssys.tables, and Oracle'sUSER_TABLES. They contain everything, including things the standard doesn't cover, such as index definitions and table sizes, but differ between databases.
Tables and columns
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- information_schema: standard views describing the database itself
SELECT table_name, table_type
FROM information_schema.tables
WHERE table_schema = 'public'
ORDER BY table_name;
SELECT column_name, data_type, is_nullable, column_default
FROM information_schema.columns
WHERE table_schema = 'public' AND table_name = 'products'
ORDER BY ordinal_position;
table_name | table_type
-------------+------------
customers | BASE TABLE
order_items | BASE TABLE
orders | BASE TABLE
products | BASE TABLE
(4 rows)
column_name | data_type | is_nullable | column_default
-------------+-------------------+-------------+----------------
product_id | integer | NO |
name | character varying | NO |
category | character varying | NO |
brand | character varying | YES |
price | numeric | NO |
stock | integer | NO |
weight_g | integer | YES |
(7 rows)
information_schema.tableshas a row for every table and view you can access.table_typedistinguishes'BASE TABLE'from'VIEW'. Filter ontable_schema, otherwise the system's own tables are listed too. In PostgreSQL, your tables are in thepublicschema by default. In MySQL, a "schema" is a database, so filter withtable_schema = DATABASE().information_schema.columnshas a row for every column, with its position, type, nullability and default.ordinal_positiongives the order in which the columns were defined.
The data_type column uses standard names: character varying rather than VARCHAR, numeric rather than DECIMAL. The length and precision are in separate columns, character_maximum_length, numeric_precision and numeric_scale.
Typical uses: finding every table with a given column (WHERE column_name = 'customer_id'), checking that a migration added a column before using it, and comparing the schemas of two databases.
Constraints and foreign keys
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Constraints and the foreign keys between tables
SELECT tc.table_name, tc.constraint_name, tc.constraint_type
FROM information_schema.table_constraints tc
WHERE tc.table_schema = 'public'
AND tc.constraint_type IN ('PRIMARY KEY', 'FOREIGN KEY', 'UNIQUE')
ORDER BY tc.table_name, tc.constraint_type, tc.constraint_name;
-- Which table references which: PostgreSQL's catalog makes this one join
SELECT conrelid::regclass AS child_table,
confrelid::regclass AS parent_table,
pg_get_constraintdef(oid) AS definition
FROM pg_constraint
WHERE contype = 'f' AND connamespace = 'public'::regnamespace
ORDER BY 1, 2;
table_name | constraint_name | constraint_type
-------------+-----------------------------+-----------------
customers | customers_referred_by_fkey | FOREIGN KEY
customers | customers_pkey | PRIMARY KEY
order_items | order_items_order_id_fkey | FOREIGN KEY
order_items | order_items_product_id_fkey | FOREIGN KEY
order_items | order_items_pkey | PRIMARY KEY
orders | orders_customer_id_fkey | FOREIGN KEY
orders | orders_pkey | PRIMARY KEY
products | products_pkey | PRIMARY KEY
(8 rows)
child_table | parent_table | definition
-------------+--------------+-------------------------------------------------------------
customers | customers | FOREIGN KEY (referred_by) REFERENCES customers(customer_id)
orders | customers | FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
order_items | products | FOREIGN KEY (product_id) REFERENCES products(product_id)
order_items | orders | FOREIGN KEY (order_id) REFERENCES orders(order_id)
(4 rows)
information_schema.table_constraints lists every primary key, foreign key, unique and check constraint with its table. Unnamed constraints get generated names, such as orders_customer_id_fkey (article 52).
Finding which columns a foreign key links is awkward in information_schema: it takes joins across key_column_usage, referential_constraints and constraint_column_usage. PostgreSQL's pg_constraint catalog is simpler: each row has the child table (conrelid), the parent table (confrelid), and pg_get_constraintdef turns it back into readable SQL. The result is a map of the schema's relationships: customers refers to itself through referred_by (article 14), orders refers to customers, and order_items to both orders and products.
The casts ::regclass and ::regnamespace are PostgreSQL conveniences that convert between internal object IDs and names, so conrelid::regclass prints a table name, and 'order_items'::regclass gives that table's ID.
PostgreSQL's catalogs: sizes and indexes
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- PostgreSQL's own catalogs know more: sizes, row estimates, indexes
ANALYZE;
SELECT c.relname AS table_name,
c.reltuples::bigint AS estimated_rows,
pg_size_pretty(pg_total_relation_size(c.oid)) AS total_size,
(SELECT COUNT(*) FROM pg_index i WHERE i.indrelid = c.oid) AS indexes
FROM pg_class c
WHERE c.relnamespace = 'public'::regnamespace AND c.relkind = 'r'
ORDER BY c.relname;
SELECT indexrelid::regclass AS index_name, pg_get_indexdef(indexrelid) AS definition
FROM pg_index
WHERE indrelid = 'order_items'::regclass;
table_name | estimated_rows | total_size | indexes
-------------+----------------+------------+---------
customers | 6 | 24 kB | 1
order_items | 9 | 24 kB | 1
orders | 6 | 24 kB | 1
products | 7 | 24 kB | 1
(4 rows)
index_name | definition
------------------+-----------------------------------------------------------------------------------------------
order_items_pkey | CREATE UNIQUE INDEX order_items_pkey ON public.order_items USING btree (order_id, product_id)
(1 row)
Some useful PostgreSQL catalogs and functions:
| Catalog or function | Contains |
|---|---|
pg_class | every table, index, view, sequence and materialized view (relkind says which) |
pg_attribute | every column |
pg_constraint | every constraint |
pg_index | index details, with pg_get_indexdef for the definition |
pg_namespace | schemas |
pg_total_relation_size, pg_size_pretty | the size of a table including its indexes, in readable units |
pg_stat_user_tables, pg_stat_user_indexes | activity statistics: scans, inserts, dead rows, index usage (article 55) |
pg_stat_activity | the sessions connected right now and what they're running |
reltuples is the planner's estimate of the row count, updated by ANALYZE and VACUUM. It's instant even for huge tables, where COUNT(*) would read everything, and is often good enough for monitoring. Each tiny table here occupies 24 kB, because space is allocated in 8 kB pages for the table, its index and other structures.
The second query shows that order_items has only its primary key index, on (order_id, product_id).
Auditing a schema with metadata
Metadata queries can check a whole schema for problems. A classic audit finds foreign key columns without an index, which make joins and parent deletes slow (article 53):
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Foreign key columns without an index: a classic metadata audit
SELECT c.conrelid::regclass AS table_name,
a.attname AS fk_column,
c.confrelid::regclass AS references_table
FROM pg_constraint c
JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = c.conkey[1]
WHERE c.contype = 'f'
AND NOT EXISTS (
SELECT 1 FROM pg_index i
WHERE i.indrelid = c.conrelid
AND i.indkey[0] = c.conkey[1])
ORDER BY 1, 2;
-- Metadata can generate SQL: the fixes, written by a query
SELECT format('CREATE INDEX ON %s (%I);', c.conrelid::regclass, a.attname) AS fix
FROM pg_constraint c
JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = c.conkey[1]
WHERE c.contype = 'f'
AND NOT EXISTS (SELECT 1 FROM pg_index i
WHERE i.indrelid = c.conrelid AND i.indkey[0] = c.conkey[1])
ORDER BY 1;
table_name | fk_column | references_table
-------------+-------------+------------------
customers | referred_by | customers
orders | customer_id | customers
order_items | product_id | products
(3 rows)
fix
-------------------------------------------
CREATE INDEX ON customers (referred_by);
CREATE INDEX ON order_items (product_id);
CREATE INDEX ON orders (customer_id);
(3 rows)
The query joins each foreign key to its first column in pg_attribute, and keeps it if no index on the table starts with that column. Three foreign keys have no index. order_items.order_id isn't listed, because it's the leading column of the primary key index, which serves lookups on it (article 55). order_items.product_id is listed: it's the second column of that index, which doesn't help a search on product_id alone. (For simplicity, the query checks only the first column of each foreign key, which is enough for single-column keys.)
The second query generates SQL from metadata: format with %s and %I builds a CREATE INDEX statement for each finding, with identifiers quoted safely if needed. In psql, ending such a query with \gexec instead of a semicolon runs each generated statement (article 44). Generating SQL from metadata is a common technique for repetitive changes: granting permissions on every table, adding an updated_at column everywhere, or truncating every table in a test database. Review generated statements before running them.
Other useful audits: tables without a primary key, columns named like foreign keys (*_id) without a constraint, unused indexes (idx_scan = 0 in pg_stat_user_indexes), and duplicate indexes with the same columns.
Comments and psql's describe commands
CREATE TABLE products (
product_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
category VARCHAR(20) NOT NULL,
brand VARCHAR(20),
price DECIMAL(8, 2) NOT NULL,
stock INTEGER NOT NULL,
weight_g INTEGER
);
INSERT INTO products VALUES
(1, 'Ridge 2 tent', 'tents', 'Alpina', 249.99, 12, 2100),
(2, 'Summit 4 tent', 'tents', 'Alpina', 489.00, 3, 4300),
(3, 'Glow head torch', 'lighting', 'Lumen', 34.50, 40, 90),
(4, 'Basecamp lantern', 'lighting', NULL, 27.00, 15, NULL),
(5, 'Trail 30 backpack', 'packs', 'Kestrel', 89.95, 22, 1150),
(6, 'Day 18 backpack', 'packs', 'Kestrel', 54.00, 0, 640),
(7, 'Merino socks', 'clothing', 'Woolly', 16.00, 75, 80);
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(40) NOT NULL,
city VARCHAR(30),
referred_by INTEGER REFERENCES customers (customer_id)
);
INSERT INTO customers VALUES
(1, 'Asha Rao', 'Pune', NULL),
(2, 'Ben Okafor', 'Leeds', 1),
(3, 'Chen Wei', 'Pune', 1),
(4, 'Dana Cruz', 'York', 2),
(5, 'Eli Novak', 'Leeds', NULL),
(6, 'Farah Haddad', NULL, 3);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER REFERENCES customers (customer_id), -- NULL = guest checkout
placed_on DATE NOT NULL,
status VARCHAR(10) NOT NULL
);
INSERT INTO orders VALUES
(101, 1, DATE '2026-03-02', 'shipped'),
(102, 2, DATE '2026-03-05', 'shipped'),
(103, 1, DATE '2026-03-09', 'delivered'),
(104, 3, DATE '2026-03-15', 'pending'),
(105, 4, DATE '2026-03-20', 'cancelled'),
(106, NULL, DATE '2026-03-22', 'shipped');
CREATE TABLE order_items (
order_id INTEGER REFERENCES orders (order_id),
product_id INTEGER REFERENCES products (product_id),
qty INTEGER NOT NULL,
unit_price DECIMAL(8, 2) NOT NULL,
PRIMARY KEY (order_id, product_id)
);
INSERT INTO order_items VALUES
(101, 1, 1, 249.99), (101, 7, 3, 16.00),
(102, 3, 2, 34.50),
(103, 5, 1, 89.95), (103, 3, 1, 34.50), (103, 7, 2, 15.00),
(104, 2, 1, 489.00),
(105, 6, 1, 54.00),
(106, 7, 1, 16.00);
-- Comments document the schema inside the database
COMMENT ON TABLE products IS 'Items for sale; one row per SKU';
COMMENT ON COLUMN products.stock IS 'Units on hand at the main warehouse';
SELECT obj_description('products'::regclass, 'pg_class') AS table_comment,
col_description('products'::regclass,
(SELECT attnum FROM pg_attribute WHERE attrelid = 'products'::regclass AND attname = 'stock')) AS stock_comment;
-- psql's \d commands are queries on the same catalogs, formatted for people
\d order_items
table_comment | stock_comment
---------------------------------+-------------------------------------
Items for sale; one row per SKU | Units on hand at the main warehouse
(1 row)
Table "public.order_items"
Column | Type | Collation | Nullable | Default
------------+--------------+-----------+----------+---------
order_id | integer | | not null |
product_id | integer | | not null |
qty | integer | | not null |
unit_price | numeric(8,2) | | not null |
Indexes:
"order_items_pkey" PRIMARY KEY, btree (order_id, product_id)
Foreign-key constraints:
"order_items_order_id_fkey" FOREIGN KEY (order_id) REFERENCES orders(order_id)
"order_items_product_id_fkey" FOREIGN KEY (product_id) REFERENCES products(product_id)
COMMENT ON attaches documentation to tables, columns, views, functions and other objects. The comments are stored in the catalogs, so they travel with the schema in backups and appear in tools and in psql's \d+ output. Explaining units, meaning and quirks there, such as "units on hand at the main warehouse", saves the next developer from guessing. MySQL uses a COMMENT clause in CREATE TABLE, and SQL Server uses extended properties.
psql's backslash commands are queries on the same catalogs, formatted for reading: \d order_items describes a table with its columns, indexes and constraints, \dt lists tables, \di indexes, \dv views, \df functions and \dn schemas. Running psql with -E (--echo-hidden) prints the catalog queries behind each command, which is a good way to learn the catalogs. Backslash commands are a psql feature, not SQL, so they don't work in application code or other clients.
Metadata in other databases
| Question | PostgreSQL | MySQL | SQL Server | Oracle | SQLite |
|---|---|---|---|---|---|
| list tables | information_schema.tables, \dt | information_schema.tables, SHOW TABLES | information_schema.tables, sys.tables | USER_TABLES, ALL_TABLES | sqlite_schema |
| describe a table | information_schema.columns, \d t | DESCRIBE t, SHOW CREATE TABLE t | sp_help 't', sys.columns | DESCRIBE t (SQL*Plus), USER_TAB_COLUMNS | PRAGMA table_info(t) |
| indexes | pg_indexes | SHOW INDEX FROM t | sys.indexes | USER_INDEXES | PRAGMA index_list(t) |
| current sessions | pg_stat_activity | SHOW PROCESSLIST | sys.dm_exec_sessions | V$SESSION | (none) |
Oracle has no information_schema. Its data dictionary views come in three scopes: USER_ for objects you own, ALL_ for objects you can access, and DBA_ for everything. SQLite stores each object's CREATE statement in sqlite_schema, called sqlite_master before version 3.33.
What's current
- PostgreSQL 17 added
pg_stat_checkpointerand moved checkpoint statistics out ofpg_stat_bgwriter, which matters for monitoring queries written for older versions. - PostgreSQL 18 added columns to
pg_stat_all_tablesfor the time spent vacuuming and analyzing each table, andpg_aiosfor asynchronous I/O. - Catalog details change between major versions, while
information_schemastays stable. Preferinformation_schemain scripts that must outlive upgrades, and test catalog queries after upgrading.
Common questions
How do I list all tables in a database?
SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' in PostgreSQL, with DATABASE() as the schema in MySQL, SHOW TABLES in MySQL, \dt in psql, USER_TABLES in Oracle, sqlite_schema in SQLite.
How do I find which tables contain a column?
SELECT table_name FROM information_schema.columns WHERE column_name = 'customer_id'.
Should I use information_schema or the system catalogs?
information_schema for portable scripts and basic questions. The catalogs for database-specific details such as index definitions, sizes and statistics.
How do I get a table's row count quickly?
COUNT(*) is exact but reads the whole table. pg_class.reltuples is an instant estimate.
Can I change the catalogs directly?
No. Use CREATE, ALTER, DROP and COMMENT. Writing to system catalogs can corrupt the database.
Summary
- Databases store their own structure in system tables you can query with SQL.
information_schemais the standard, portable layer:tables,columns,table_constraints,key_column_usageand more.- System catalogs such as
pg_class,pg_attribute,pg_constraintandpg_indexhold everything, including sizes and index definitions. - Metadata queries can audit a schema, for example for unindexed foreign keys, and generate SQL to fix it.
COMMENT ONdocuments objects inside the database. psql's\dcommands are catalog queries.- Every database has its own commands and views:
SHOWandDESCRIBEin MySQL,sys.*in SQL Server,USER_*in Oracle,PRAGMAin SQLite.
Practice questions
Write a query that lists every column in the public schema whose name ends in _id, with its table, sorted by table and column.
Answer
SELECT table_name, column_name
FROM information_schema.columns
WHERE table_schema = 'public' AND column_name LIKE '%\_id'
ORDER BY table_name, column_name;
The backslash escapes the underscore, which is otherwise a single-character wildcard in LIKE (article 7).
List the views in the public schema using information_schema.
Answer
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'public' AND table_type = 'VIEW'
ORDER BY table_name;
information_schema.views also lists them, with their definitions.
Why does the unindexed foreign key audit not report order_items.order_id, but does report order_items.product_id?
Answer
The primary key index is on (order_id, product_id). Its leading column is order_id, so it serves lookups by order_id. product_id is only the second column, which doesn't help searches on product_id alone, so that foreign key needs its own index.
Write a query that generates a GRANT SELECT ON ... TO reporting; statement for every table in the public schema.
Answer
SELECT format('GRANT SELECT ON %I.%I TO reporting;', table_schema, table_name)
FROM information_schema.tables
WHERE table_schema = 'public' AND table_type = 'BASE TABLE'
ORDER BY table_name;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO reporting does the same in one statement in PostgreSQL (article 58).
Previous: SQL Views and Materialized Views
Next: Users, Roles and Privileges: GRANT, REVOKE and Row-Level Security

More in SQL Course
Quiz: SQL Dialect Differences (PostgreSQL, MySQL, SQL Server, Oracle, SQLite)
Twenty-four questions on how the major SQL databases differ: limiting rows, concatenation, empty strings, identifier case, upserts, identity columns, transactional DDL, error handling, isolation defaults, booleans, set operations, RETURNING, dates and typing.
Quiz: SQL Delicate Details
Twenty-five questions on SQL's subtle corners: NULLs in aggregates, IN and CHECK, sort order of NULLs, rounding, CHAR padding, window frame defaults, identity gaps, LIKE escapes, empty groups, set operations and multi-column updates.
Quiz: SQL Interview Questions
Thirty SQL questions of the kind asked in developer and analyst interviews: WHERE vs HAVING, DELETE vs TRUNCATE, keys, joins, duplicates, Nth-highest values, window functions, ACID, isolation, locking, indexes, views, procedures and performance.
Quiz: SQL Course Final Exam (All 15 Parts)
The final exam for the SQL course: thirty questions across all fifteen parts, from query processing, NULLs, joins and aggregation through windows, data changes, types, design, indexes, security, transactions, procedural SQL and tuning.
Discussion
Sign in to ask a question or share what you learned.