Foreign Key Constraints
What is Foreign Key?
- A FOREIGN KEY in one table points to a PRIMARY KEY in another table.
- FOREIGN KEY constraint can contain null values; however, if any column of a composite FOREIGN KEY constraint contains null values
- Foreign keys can be specified during alter table or create table.
Table categories
| column name | characteristic |
| cat_id | Primary Key |
| Category |
Table Articles
| column name | characteristic |
| article_id | Primary Key |
| Title | |
| Description | |
| full_article | |
cat_id |
Foreign Key |
CREATE TABLE articles
(
article_id numeric(4),
title varchar(255) not null,
description varchar(255) ,
full_article varchar(255) not null,
Primary Key (article_id),
Foreign Key (cat_id) references categories(cat_id)
)
(
article_id numeric(4),
title varchar(255) not null,
description varchar(255) ,
full_article varchar(255) not null,
Primary Key (article_id),
Foreign Key (cat_id) references categories(cat_id)
)
Below are examples for specifying a foreign key by altering a table. This assumes that the ORDERS table has been created, and the foreign key has not yet been put in:
ALTER TABLE articles
ADD FOREIGN KEY (cat_id) REFERENCES CUSTOMER(cat_id);
ADD FOREIGN KEY (cat_id) REFERENCES CUSTOMER(cat_id);
