next up previous contents index
Next: Foreign Key/REFERENCES Up: Constraints Previous: UNIQUE

    
PRIMARY KEY

The PRIMARY KEY constraint, which marks the column that uniquely identifies each row, is a combination of UNIQUE and NOT NULL constraints. With this type of constraint, UNIQUE prevents duplicates, and NOT NULL  prevents NULL values in the column. Figure [*] shows the creation of a PRIMARY KEY column.  

        test=> CREATE TABLE primarytest (col INTEGER PRIMARY KEY);
        NOTICE:  CREATE TABLE/PRIMARY KEY will create implicit index 'primarytest_pkey' for table 'primarytest'
        CREATE
        test=> \d primarytest 
              Table "primarytest"
         Attribute |  Type   | Modifier 
        -----------+---------+----------
         col       | integer | not null
        Index: primarytest_pkey
 

Notice that an index   is created automatically, and the column is defined as NOT NULL.

Just as with UNIQUE, a multicolumn PRIMARY KEY constraint must be specified on a separate line. In Figure [*], col1 and col2 are combined to form the primary key.  

        test=> CREATE TABLE primarytest2 (
        test(>                            col1 INTEGER, 
        test(>                            col2 INTEGER, 
        test(>                            PRIMARY KEY(col1, col2)
        test(>                           );
        NOTICE:  CREATE TABLE/PRIMARY KEY will create implicit index 'primarytest2_pkey' for table 'primarytest2'
        CREATE
 

A table cannot have more than one PRIMARY KEY specification. Primary keys have special meaning when using foreign keys, which are covered in the next section. 


Bruce Momjian
2001-05-09