Categories
Sql Server

How to create FOREIGN KEY Constraint in Sql server

How to create FOREIGN KEY Constraint in Sql server

A FOREIGN KEY in any table points to a PRIMARY KEY in another table.

Let us Create a table Hightech:-

Hightech table:

Id FirstName City
1 Jai Delhi
2 Om Kolkata
3 Hari Haryana

Here In table hightech Id is Primary Key of table Hightech

The Hightech2 table:

SaleId Sale_Quantity Id
1110 10000 1
2232 2005 2
390 1678 3

In Hightech2 table SaleId is Primary Key of the Hightech2 Table.

In Hightech2 table Id is Foreign key of table hightech2 which is Primary Key in hightech table.

The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables.

Query:-
CREATE TABLE hightech2
(
SaleId int NOT NULL PRIMARY KEY,
sale_quantity int NOT NULL,
Id int FOREIGN KEY REFERENCES hightech(Id)
)

Alter Query For already Created Tables :-
ALTER TABLE Orders
ADD CONSTRAINT fk_Orders
FOREIGN KEY (Id)
REFERENCES sale(Id)

Drop already created Foreign constraints:
ALTER TABLE Orders
DROP CONSTRAINT fk_Orders

One reply on “How to create FOREIGN KEY Constraint in Sql server”

Comments are closed.