Adding referential constraints to existing tables
You can use the ALTER TABLE statement to add referential constraints to existing tables.
Before you begin
About this task
Assume that the tables in the sample application (the Db2 sample activity table, project table, project activity table, employee table, and department table) already exist, have the appropriate column definitions, and are already populated.
Now, suppose that you want to define relationships among the sample tables by adding primary and foreign keys with the ALTER TABLE statement. The following rules apply to these relationships:
- An existing table must have a unique index on its primary key columns before you can add the primary key. The index becomes the primary index.
- You must add the parent key of the parent table before adding the corresponding foreign key of the dependent table.
You can build the same referential structure in several different ways; however, the following process might be the simplest to understand.
Procedure
To add a referential constraint to an existing table:
Examples
- Create the DEPT table and define its primary key on the DEPTNO column. The PRIMARY KEY clause of the CREATE TABLE statement defines the primary key.
CREATE TABLE DEPT ⋮ PRIMARY KEY (DEPTNO);
- Create the EMP table and define its primary key as EMPNO and its foreign key as DEPT. The FOREIGN KEY clause of the CREATE TABLE statement defines the foreign key.
CREATE TABLE EMP ⋮ PRIMARY KEY (EMPNO) FOREIGN KEY (DEPT) REFERENCES DEPT (DEPTNO) ON DELETE SET NULL;
- Alter the DEPT table to add the definition of its foreign key, MGRNO.
ALTER TABLE DEPT FOREIGN KEY (MGRNO) REFERENCES EMP (EMPNO) ON DELETE RESTRICT;