Constraints may be added in a limited fashion after a table has been created. As of PostgreSQL 7.1.x, only foreign key constraints may be added to an existing table column. The following is the syntax to add a constraint to a table with the name table_name , and a constraint named constraint_name , defined as constraint_definition :

  ALTER TABLE table_name
        ADD CONSTRAINT constraint_name constraint_definition

The syntax of the constraint_definition is dependent on the type of constraint you wish to add. As foreign keys are the only supported constraint with the ADD CONSTRAINT (as of PostgreSQL 7.1.x), the syntax for adding a foreign key to the editions table (which references the books table's id column) is demonstrated in Example 4-11 .

Example 4-11. Adding a Foreign Key to a Table

booktown=# ALTER TABLE editions 
booktown-#       ADD CONSTRAINT foreign_book 
booktown-#       FOREIGN KEY (book_id) REFERENCES books (id);
NOTICE:  ALTER TABLE ... ADD CONSTRAINT will create implicit trigger(s)
for FOREIGN KEY check(s)
CREATE

See the section called Constraints in Chapter 5 for more detailed information on constraints, their purpose, and their syntax.