SQL FOREIGN KEY


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.

Example

customer_detail Table :
c_idCustomer_Nameaddress
111AshwaniDelhi
112SachinHaryana
113SounRohtak
order_detail Table :
Order_idOrder_Namec_id
10Order1111
11Order2113
12Order3112

In customer_detail table, c_id is the primary key which is set as foreign key in order_detail table. The value that is entered in c_id which is set as foreign key in order_detail table must be present in customer_detail table where it is set as primary key. This prevents invalid data to be inserted into c_id column of order_detail table.

CREATE TABLE order_detail(order_id INT PRIMARY KEY,
order_name VARCHAR(60) NOT NULL,
c_id INT FOREIGN KEY REFERENCES customer_detail(c_id))

Share this article on