COMMENT ON Documents Schema Objects

Attach documentation to tables, columns, and indexes with COMMENT ON, then read it back from the system catalogs.

SqlConfig Management

Code

snippet
CREATE TABLE orders (
  id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  status text NOT NULL,
  total numeric(12, 2) NOT NULL
);

CREATE INDEX orders_status_idx ON orders (status);

COMMENT ON TABLE orders IS 'Customer orders, one row per checkout';
COMMENT ON COLUMN orders.status IS 'pending, paid, shipped, or cancelled';
COMMENT ON INDEX orders_status_idx IS 'Speeds up status dashboards';

SELECT obj_description('orders'::regclass, 'pg_class') AS table_comment,
       col_description('orders'::regclass, 2) AS status_comment;

SELECT indexrelid::regclass AS index_name,
       obj_description(indexrelid, 'pg_class') AS index_comment
FROM pg_index
WHERE indrelid = 'orders'::regclass;

-- Passing NULL removes a comment
COMMENT ON COLUMN orders.status IS NULL;

How it works

What runs here is SELECT / CREATE — pg_index are the objects involved.

Breaking the statements into their working parts: a WHERE clause constraining which rows the statement operates on; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; a GENERATED ALWAYS/GENERATED BY clause that computes the column value.

Applying it

Run the statement against the pg_index table.

Statements that matter

SELECT indexrelid::regclass AS index_name,
       obj_description(indexrelid, 'pg_class') AS index_comment
FROM pg_index
WHERE indrelid = 'orders'::regclass;
SELECT obj_description('orders'::regclass, 'pg_class') AS table_comment,
       col_description('orders'::regclass, 2) AS status_comment;
CREATE TABLE orders (
  id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  status text NOT NULL,
  total numeric(12, 2) NOT NULL
);

Interactive Tools for This Topic

FAQ

What objects does the SQL involve?
The references are `pg_index`.