SQL FOREIGN KEY
A foreign key is a field (or fields) that points to the primary key of another table. The purpose of the foreign key is to ensure referential integrity of the data. In other words, only values that are supposed to appear in the database are permitted.
For example, say we have two tables, a CUSTOMER
table that includes all customer data, and an ORDER
table that includes all customer orders. The constraint here is that all orders must be associated with a customer that is already in the CUSTOMER table. In this case, we will place a foreign key on the ORDERS table and have it relate to the primary key of the CUSTOMER table. This way, we can ensure that all orders in the ORDERS table are related to a customer in the CUSTOMER table. In other words, the ORDERS table cannot contain information on a customer that is not in the CUSTOMER table.
The structure of these two tables will be as follows:
Table Customer
column name | characteristic |
SID | Primary Key |
Last_Name | |
First_Name |
Table Orders
column name | characteristic |
Order_ID | Primary Key |
Order_Date | |
Customer_SID | Foreign Key |
Amount |
In the above example, the Customer_SID
column in the Order table is a foreign key pointing to the SID column in the Customer table.
Below we show examples of how to specify the foreign key when creating the ORDER table:
MySQL:
1 2 3 4 5 6 7 | CREATE TABLE Order (Order_ID integer, Order_Date date, Customer_SID integer, Amount double, Primary Key (Order_ID), Foreign Key (Customer_SID) references Customer(SID)); |
Oracle:
1 2 3 4 5 | CREATE TABLE Order (Order_ID integer primary key, Order_Date date, Customer_SID integer references Customer(SID), Amount double); |
SQL Server:
1 2 3 4 5 | CREATE TABLE Order (Order_ID integer primary key, Order_Date DateTime, Customer_SID integer references Customer(SID), Amount double); |
Below are examples for specifying a primary key by altering a table. This assumes that the Orders table has been created, and the foreign key has not yet been put in:
MySQL:
1 2 | ALTER TABLE orders ADD FOREIGN KEY (customer_sid) REFERENCES customer(sid); |
Oracle:
1 2 | ALTER TABLE orders ADD (CONSTRAINT fk_orders1) FOREIGN KEY (customer_sid) REFERENCES customer(sid); |
SQL Server:
1 2 | ALTER TABLE orders ADD FOREIGN KEY (customer_sid) REFERENCES customer(sid); |