0% found this document useful (0 votes)
2 views

SQL Foreign Key

A foreign key is a column or set of columns that establishes a link between two tables by matching values to a primary key in another table. The document provides examples of creating tables with foreign keys, specifically illustrating the relationship between a CUSTOMERS table and an ORDERS table. It also includes SQL commands for adding and dropping foreign key constraints.

Uploaded by

itxjack100
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

SQL Foreign Key

A foreign key is a column or set of columns that establishes a link between two tables by matching values to a primary key in another table. The document provides examples of creating tables with foreign keys, specifically illustrating the relationship between a CUSTOMERS table and an ORDERS table. It also includes SQL commands for adding and dropping foreign key constraints.

Uploaded by

itxjack100
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

SQL - FOREIGN KEY

http://www.tutorialspoint.com/sql/sql-foreign-key.htm Copyright © tutorialspoint.com

A foreign key is a key used to link two tables together. This is sometimes called a referencing key.

Foreign Key is a column or a combination of columns whose values match a Primary Key in a
different table.

The relationship between 2 tables matches the Primary Key in one of the tables with a
Foreign Key in the second table.

If a table has a primary key defined on any fields, then you can not have two records having the
same value of that fields.

Example:
Consider the structure of the two tables as follows:

CUSTOMERS table:

CREATE TABLE CUSTOMERS(


ID INT NOT NULL,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);

ORDERS table:

CREATE TABLE ORDERS (


ID INT NOT NULL,
DATE DATETIME,
CUSTOMER_ID INT references CUSTOMERS(ID),
AMOUNT double,
PRIMARY KEY (ID)
);

If ORDERS table has already been created, and the foreign key has not yet been set, use the
syntax for specifying a foreign key by altering a table.

ALTER TABLE ORDERS


ADD FOREIGN KEY (Customer_ID) REFERENCES CUSTOMERS (ID);

DROP a FOREIGN KEY Constraint:


To drop a FOREIGN KEY constraint, use the following SQL:

ALTER TABLE ORDERS


DROP FOREIGN KEY;
Loading [MathJax]/jax/output/HTML-CSS/fonts/TeX/fontdata.js

You might also like