134

How can I add comment to column in PostgreSQL?

create table session_log (
                UserId int index not null,
                PhoneNumber int index); 
lospejos
  • 1,976
  • 3
  • 19
  • 35
user3600910
  • 2,839
  • 4
  • 22
  • 36

1 Answers1

209

Comments are attached to a column using the comment statement:

create table session_log 
( 
   userid int not null, 
   phonenumber int
); 

comment on column session_log.userid is 'The user ID';
comment on column session_log.phonenumber is 'The phone number including the area code';

You can also add a comment to the table:

comment on table session_log is 'Our session logs';

Additionally: int index is invalid.

If you want to create an index on a column, you do that using the create index statement:

create index on session_log(phonenumber);

If you want an index over both columns use:

create index on session_log(userid, phonenumber);

You probably want to define the userid as the primary key. This is done using the following syntax (and not using int index):

create table session_log 
( 
   UserId int primary key, 
   PhoneNumber int
); 

Defining a column as the primary key implicitly makes it not null

  • 2
    Seems that PG not offers standard syntax for comment on CREATE TABLE clause... Why not? – Peter Krauss Nov 29 '19 at 14:06
  • 9
    @PeterKrauss: there is no standard for comments on CREATE TABLE statements (Postgres uses the same syntax as Oracle) –  Nov 29 '19 at 14:07
  • 1
    It seems that pgAdmin won't show column comments but this works in psql (shows them rightmost, under "Description"): `\d+ my_table` – gherson Apr 08 '22 at 16:40
  • 1
    Rare to see SQL-comments, partly because there is **no incentive, the syntax is ugly and redundant**. The ideal comment-syntax for programmers, less verbose and more human-readable, is like Hive SQL: **at CREATE clause**, [see here an example](https://discuss.itversity.com/t/adding-comments-to-columns-and-tables/18252). – Peter Krauss Oct 29 '22 at 17:03
  • @PeterKrauss: I completely disagree. We use comments all the time. And the syntax is neither ugly nor redundant. It allows you to _change_ an existing comment or add a new one with the same command. How do you change a comment if you can only specify it during the CREATE TABLE. –  Oct 29 '22 at 17:30
  • 1
    @a_horse_with_no_name, sorry, the suggestion is **not** to abandon a standard, it's just to add **optional COMMENT on CREATE clause**... You agree that an option would be beneficial? – Peter Krauss Oct 29 '22 at 17:44
  • @PeterKrauss: again: **there is no standard** for adding comments to tables, views, columns, indexes or constraints –  Oct 29 '22 at 18:21
  • @a_horse_with_no_name, sorry my English, I'm trying an "imagine it" talk, to check your opinion. It does not exist, it is a **suggestion to add a new feature**, without conflict with the previous standard. – Peter Krauss Oct 29 '22 at 20:17