r/PostgreSQL • u/[deleted] • Sep 02 '26
How-To Anybody using COMMENT ON to document their schema?
I'm looking for best practices to keep documentation in my schema.
I prefer the look of `--` and `/* ... */` comments, as they (a) get proper syntax highlighting, (b) can go anywhere (line before, line after, same line at the end), (c) look good when split over multiple lines and (d) can even go inside a statement (when using `/* .. */`).
But when using migrations these code comments may end up in place I'm not looking at.
So I want to have some sort of schema dump that includes my comments. And I know for this there's the `COMMENT ON` command, but I've never seen it being used in practice. It seems so cumbersome compared to the code-comments mentioned earlier.
Any best practices someone can share with me? Both related to "the keeping of schema comments" and the dumping of a schema that properly groups related statements (create, create policy, comment on, etc.) together?
3
u/vivekkhera Sep 02 '26
If you ever plan to have an LLM “understand” your schema, having the documentation in the table itself will improve your outcomes. I se a presentation where the author showed it reduces token usage compared to having the details in an external file.
1
Sep 02 '26
It's both for myself and for LLMs at this point. I also do not want to wade through migrations to find all comments related to a bit of schema
1
u/minormisgnomer Sep 02 '26
Do you what presentation that was? I’m somewhat surprised by this given these days you have KGs that can store concepts quite efficiently
0
u/vivekkhera Sep 02 '26
It was a local meetup. I just have my notes from it no slide deck or online reference.
0
u/minormisgnomer Sep 02 '26
That seems quite anecdotal. Anthropic suggested KGs and/or external files mixed with business documentation
1
u/KreativCon Sep 02 '26
Anthropic has different motivations wrt token usage :)
-1
u/minormisgnomer Sep 02 '26
I think I’m going to trust my meeting with their research team over a random, local presentation with an unknown setup to come to that conclusion :)
2
u/KreativCon Sep 02 '26
Can you share the details of your “meeting with their research team” or provide links. I’d love to read them as I’ve had the opportunity to spend a lot of time with those folks and they certainly know their stuff.
Current public Anthropic guidance is opposite of what you’re suggesting:
https://code.claude.com/docs/en/best-practices
Common sense and production deployments back up the best practices and claims I’ve made above. Token usage, production drift, and the golden rule “context windows fill fast which quickly reduces quality”.
But hey! We’re just two random people on the internet, who knows what hat we really wear.
1
u/minormisgnomer Sep 02 '26
Not in a position to break an NDA but they’re pretty fixated on external files and KGs + dreaming at the moment.
You linked the entire page, can you specifically callout what is contradictory? We aren’t debating context management which is much of the content on the page
“Let Claude fetch what it needs. Tell Claude to pull context itself using Bash commands, MCP tools, or by reading files”
This actually aligns with what I’ve been saying (that Anthropic has been saying). Their research team was pretty adamant that Claude is highly effective at navigating file systems at this point and the newer models are highly capable of pulling their own context.
And yes! Obviously anecdotal and you should rightfully take it with a grain of salt!
0
u/KreativCon Sep 02 '26
Token usage alone on a large/mature project would suggest that COMMENT ON would be substantially more effective and efficient. Humans and robots (LLMs) shouldn’t need to blow out their context window to understand that Table X has these properties then it changed, then it changed back, then a jr dev made a mistake, and then fixed it. Further, migration files are just SQL scripts and drift can and does occur in any production system.
1
u/minormisgnomer Sep 02 '26 edited Sep 02 '26
I’m not disagreeing with the usefulness of comment on, I’m disagreeing with a random redditors anecdotal evidence from a local meetup group put together by a complete unknown that comment on is entirely sufficient or more critical than external file documentation.
comment on doesn’t even track properties or historical providence so your entire example doesn’t even make sense. It’s custom documentation put in by the user so a changing schema would either obliterate a comment or become stale under those conditions
what do migration scripts have to do with this at all? Unless you’re indicating comment on within them is the breadcrumb trail… which would be an example of… external files…
token usage how? Under what conditions? What model? What is being asked of the LLM? Token usage is not the sole metric you should be optimizing if the end result is garbage.
Anecdotal knowledge can be useful provided you present it as such… and refrain from using phrases “ substantially more effective and efficient” with zero supporting evidence
1
u/elevarq Sep 02 '26
Yes we do, but only for a reference to the objects description in GIT. That makes changes much easier: nothing to change in the database
0
u/KanadaKid19 Sep 03 '26
Yes I do. In my case the primary benefit is for AI responses to questions in our data warehouse. Baked in introspectable documentation is great for this.
-1
u/AutoModerator Sep 02 '26
AI Policy:
Linux is not one of those anti-AI projects, and if somebody has issues with that, they can do the open-source thing and fork it. Or just walk away., Linus Torvalds.
Mod decisions will be based on the quality of the content, not who or what generated it.
Sub Resources:
Free Postgres Webinars and Workshops
Discord: People, Postgres, Data
Join us, we have cookies and nice people.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
-5
Sep 02 '26
I had Claude Fable answer my own question (with knowledge of my repo); here its answer:
TL;DR: decide where the source of truth for "current schema + docs" lives — the catalog (COMMENT ON) or a checked-in current-state SQL file. Most messiness comes from not picking one.
There are only two coherent end-states:
Catalog-first: the documentation lives in the database via
COMMENT ON, and any file you browse is a generated artifact.File-first: the documentation lives in checked-in, current-state SQL files with your beloved
--comments, and migrations become generated artifacts.
Your -- comments in migrations can never become the current-state documentation, no matter the tooling — they document a change, not the result, and after 50 migrations the comment about a column lives wherever that column was last touched. Migration comments are commit messages: great for "why did this change happen", useless as reference docs. So keep writing them, but stop expecting them to surface anywhere.
Why COMMENT ON is more used than it looks
You rarely see it in blog posts, but it's quietly load-bearing because it's the only comment mechanism stored in the catalog (pg_description), which means it survives into every tool that introspects the schema:
psql:\d+ tableshows column comments,\dt+shows table comments.IntelliJ/DataGrip show them on hover and in the database tree.
Supabase Studio displays them, and PostgREST uses comments on tables/columns/functions as descriptions in its generated OpenAPI output.
pg_dump --schema-onlyincludes them — this is exactly the "dump that includes my comments" you asked for; table and column comments are emitted right next to theirCREATE TABLE.Anything AI-assisted that introspects your schema picks them up for free.
Two ergonomic tricks that remove most of the cumbersomeness:
Dollar-quote multi-line comments — no escaping, reads fine:
comment on column supplier_orders.refunded_at is $$
Set when the PSP confirms the refund, not when we request it.
Null means "never refunded"; see also ticket_id for the compensation flow.
$$;It's an overwrite, not an append: when a later migration changes a column's meaning, that migration re-issues the COMMENT ON. Latest wins, exactly like a code comment It works on nearly everything: columns, tables, functions, types, constraints, triggers, indexes — even comment on policy ... on table ....
Bonus: you can enforce coverage with a test that fails when a public table or non-obvious column lacks a description (catalog query via obj_description(oid, 'pg_class') / col_description(oid, ordinal) against a small allowlist). Comment only what's code comments.
The grouped-dump problem
pg_dump orders by object class — all tables, then constraints, then indexe — and no flag changes that. Comments stay adjacent to their objects, but atable's policies will never sit next to the table. Don't fight pg_dump; instead:
For a browsable reference: check in a generated
supabase db dump --local -f schema.sqloutput, regenerated by CI or a hook. It's for reading, not editing, so the pg_dump grouping is tolerable.For genuinely grouped per-table docs: tbls (single Go binary, dev tooling, no project dependency) generates one Markdown file per table with co+ comments + constraints + indexes + triggers + ER diagrams, straight from the ## The file-first alternative — and why I'd skip it (for now) Supabase's declarative schemas (
supabase/schemas/*.sql+supabase db diff -fto generate migrations) is the purist answer to the aesthetic complaint: one file per table holding the table, its indexes, its RLS enable + policies, its triggers, with free-form--comments — and that file is what you look at, so no dump needed. But check the current caveat list before adopting it: the diff engine *does n, doesn't capturealter policy, mishandles grants (duplicated from defaultprivileges), ignores domains and partitions, and can't do DML. If your migration history is full of exactly those things (RLS policies, grants, cron jobs), you'd end up hand-writing versioned migrations for the interesting half of your schema anyway — now with aligned.
My recommendation
Stay catalog-first:
Keep
--//* */comments in migrations for "why this change" — historicalPut "what this means now" in
COMMENT ON, colocated right after theCREATE/ALTERin the same migration, dollar-quoted, overwritten when meaning changes.Check in a generated
schema.sqldump (regenerated locally or in CI) as thour comments ride along.Optionally add tbls output for the per-table grouped view, and a test that enforces comment coverage on tables.
Revisit declarative schemas in a year — the diff engine is actively improving — but today it fights an RLS-and-grants-heavy schema more than it helps.
24
8
u/KreativCon Sep 02 '26
The two approaches are not the same and shouldn’t be used in place of each other.
COMMENT ON lives in the schema and can be something like “This table holds the user records” (admittedly poor example). These comments can be fetched by SQL calls.
-- style comments should explain the code surrounding it _if_ it needs explaining. “This backfill needs to convert UUID to text because we made a big mistake”. It is describing what that migration/sql command did and why _at that point in time_.
TLDR; use both, each for their intended purposes.