// SQL snippet

Comment a column and its table

A column comment tells the next reader what the value means and what unit it is in, and it travels with the schema. Each engine stores these comments differently.

Main statement
PostgreSQL
还支持
SQL Server MySQL

The task

Nobody remembers what a column is for or what units a value carries, and the answer currently lives in one person's head. Write it into the schema.

The snippet

Written for PostgreSQL. Versions for SQL Server and MySQL are under Variations.

PostgreSQL
COMMENT ON COLUMN public.users.email
  IS 'Primary login address, verified at signup';
COMMENT ON TABLE public.users
  IS 'Application accounts; one row per registered user';

工作原理

PostgreSQL stores comments in pg_description, keyed to the object, and COMMENT ON replaces any existing text, so re-running it is safe; COMMENT ... IS NULL removes one. psql shows column comments in \d+ output, and col_description(table_oid, column_number) reads one back. Dropping and recreating a column or table drops its comment, so migrations that rebuild objects must re-apply them.

Variations

MySQL

MySQL
-- the comment is part of the column definition, so MODIFY must
-- restate the full type, nullability and default or lose them
ALTER TABLE users
  MODIFY COLUMN email VARCHAR(320) NOT NULL
  COMMENT 'Primary login address, verified at signup';
-- table comment:
ALTER TABLE users COMMENT = 'Application accounts';

SQL Server

SQL Server
EXEC sp_addextendedproperty
    @name = N'MS_Description',
    @value = N'Primary login address, verified at signup',
    @level0type = N'SCHEMA', @level0name = N'dbo',
    @level1type = N'TABLE',  @level1name = N'Users',
    @level2type = N'COLUMN', @level2name = N'Email';
-- re-running needs sp_updateextendedproperty, or drop first

Questions that come up

Can I read all column comments at once?

Yes. On PostgreSQL, select col_description(format('%I.%I', table_schema, table_name)::regclass, ordinal_position) alongside information_schema.columns. MySQL has them in information_schema.columns.column_comment. On SQL Server, fn_listextendedproperty(N'MS_Description', N'SCHEMA', N'dbo', N'TABLE', N'Users', N'COLUMN', NULL) returns one row per commented column.

Keep reading

// snippets are better with a schema brain

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.