163

How can I add comment to column in PostgreSQL?

create table session_log (
                UserId int index not null,
                PhoneNumber int index); 

1 Answer 1

251

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

Sign up to request clarification or add additional context in comments.

8 Comments

Seems that PG not offers standard syntax for comment on CREATE TABLE clause... Why not?
@PeterKrauss: there is no standard for comments on CREATE TABLE statements (Postgres uses the same syntax as Oracle)
It seems that pgAdmin won't show column comments but this works in psql (shows them rightmost, under "Description"): \d+ my_table
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.
@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?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.