Question

Can I define a primary key according to three attributes? I am using Visual Paradigm and Postgres.

CREATE TABLE answers (
  time                          SERIAL NOT NULL, 
  "{Users}{userID}user_id"     int4 NOT NULL, 
  "{Users}{userID}question_id" int4 NOT NULL, 
  reply                        varchar(255), 
  PRIMARY KEY (time, "{Users}{userID}user_id", "{Users}{userID}question_id"));

A picture may clarify the question.

Was it helpful?

Solution

Yes you can, just as you showed.(though I question your naming of the 2. and 3. column.)

From the docs:

"Primary keys can also constrain more than one column; the syntax is similar to unique constraints:

CREATE TABLE example (
    a integer,
    b integer,
    c integer,
    PRIMARY KEY (a, c)
);

A primary key indicates that a column or group of columns can be used as a unique identifier for rows in the table. (This is a direct consequence of the definition of a primary key. Note that a unique constraint does not, by itself, provide a unique identifier because it does not exclude null values.) This is useful both for documentation purposes and for client applications. For example, a GUI application that allows modifying row values probably needs to know the primary key of a table to be able to identify rows uniquely.

A table can have at most one primary key (while it can have many unique and not-null constraints). Relational database theory dictates that every table must have a primary key. This rule is not enforced by PostgreSQL, but it is usually best to follow it. "

OTHER TIPS

Yes, you can. There is just such an example in the documentation.. However, I'm not familiar with the bracketed terms you're using. Are you doing some variable evaluation before creating the database schema?

  1. yes you can
  2. if you'd run it - you would see it in no time.
  3. i would really, really, really suggest to rethink naming convention. time column that contains serial integer? column names like "{Users}{userID}user_id"? oh my.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top