Creating Foreign Keys

Each foreign key relationship relates a candidate key (primary key and unique constraint) in one column to a column in another table, which becomes the foreign key.

For example, you can create a table named emp_skill, which holds a description of each employee's skill level for each skill in which they are qualified, as follows:

CREATE TABLE emp_skill(
emp_id INTEGER NOT NULL,
skill_id INTEGER NOT NULL,
"skill level" INTEGER NOT NULL,
PRIMARY KEY( emp_id, skill_id ),
FOREIGN KEY REFERENCES employee,
FOREIGN KEY REFERENCES skill
)

The emp_skill table definition has a primary key that consists of two columns: the emp_id column and the skill_id column. An employee may have more than one skill, and so appear in several rows, and several employees may possess a given skill, so that the skill_id may appear several times.

The emp_skill table also has two foreign keys. The foreign key entries indicate that the emp_id column must contain a valid employee number that is a primary key in the employee table from the employee table, and that the skill_id must contain a valid entry that is a primary key in the skill table from the skill table.

A table can only have one primary key defined, but it may have as many foreign keys as necessary.

You cannot create foreign key constraints on temporary tables of any kind—local, global, or automatic.

For more information about valid strings and identifiers, see Reference: Building Blocks, Tables, and Procedures > SQL Language Elements.

For more information about using primary and foreign keys, see Chapter 9, “Ensuring Data Integrity”

Related concepts
Additional Dbspaces
Creating Primary Keys
Entity and Referential Integrity
Star Joins