inheritancecommentspsqlsql-view

Can view in psql inherit comment from table on simple columns?


Suppose I have dummy table like this:

CREATE TABLE test_table (value INT);

And a comment on that column:

COMMENT ON COLUMN test_table.value IS 'Test comment';

Then, I create a view on my table:

CREATE VIEW test_view AS SELECT * FROM test_table;

But, it doesn't inherit the comment on the column:

\d+ test_table;
                                Table "public.test_table"
 Column |  Type   | Collation | Nullable | Default | Storage | Stats target | Description 
--------+---------+-----------+----------+---------+---------+--------------+-------------
 value  | integer |           |          |         | plain   |              | Test comment


\d+ test_view;
                          View "public.test_view"
 Column |  Type   | Collation | Nullable | Default | Storage | Description 
--------+---------+-----------+----------+---------+---------+-------------
 value  | integer |           |          |         | plain   | 

Is there a way for a view to inherit comment from the table? Is this even a reasonable thing to ask for - I'd only expect to have this available for trivial column definitions in view, where a column is simply selected from other table, where there is some calculation in column, I wouldn't expect this to be possible.

I've looked here but doesn't seem to show up: https://www.postgresql.org/docs/17/sql-comment.html

I take this likely isn't possible but wanted to double check if someone has any suggestions


Solution

  • In PostgreSQL, views do not automatically inherit comments from underlying table columns. Because views are considered separate objects, and each column in a view is a new entity, even if it directly maps to a table column. PostgreSQL doesn’t propagate comments from table columns to view columns, since views can contain complex expressions, transformations, or joins, and it wouldn’t always make sense to inherit comments from the underlying table.

    If you need to keep comments in your view you can add it manually:

    COMMENT ON COLUMN test_view.value IS 'Test comment';
    

    But I think it is not what you want, but there is no solution except writing your own function to automate the transfer of comments from a table to a view, but for me it is not a good idea.

    Have a nice day.