Wednesday, May 7, 2008

What is a foreign key?

What is a foreign key?

A foreign key means that values in one table must also appear in another table.

The referenced table is called the parent table while the table with the foreign key is called the child table. The foreign key in the child table will generally reference a primary key in the parent table.

A foreign key can be defined in either a CREATE TABLE statement or an ALTER TABLE statement.

 

Using a CREATE TABLE statement

The syntax for creating a foreign key using a CREATE TABLE statement is:

CREATE TABLE table_name
(column1 datatype null/not null,
column2 datatype null/not null,
...
CONSTRAINT fk_column
  FOREIGN KEY (column1, column2, ... column_n)
  REFERENCES parent_table (column1, column2, ... column_n)
);

 

For example:

CREATE TABLE supplier

(

supplier_id

numeric(10)

not null,

 

supplier_name

varchar2(50)

not null,

 

contact_name

varchar2(50),

 

 

CONSTRAINT supplier_pk PRIMARY KEY (supplier_id)

);

 

CREATE TABLE products

(

product_id

numeric(10)

not null,

 

supplier_id

numeric(10)

not null,

 

CONSTRAINT fk_supplier

 

  FOREIGN KEY (supplier_id)

 

  REFERENCES supplier(supplier_id)

);

In this example, we've created a primary key on the supplier table called supplier_pk. It consists of only one field - the supplier_id field. Then we've created a foreign key called fk_supplier on the products table that references the supplier table based on the supplier_id field.

No comments:

Post a Comment