SQL FOREIGN KEY Constraint With Example

.
 Foreign Key in SQL - How to use Foreign key in SQL 

Foreign Key in SQL 


What is a Foreign Key?


How to use Foreign key in SQL? 



SQL FOREIGN KEY on CREATE TABLE

My SQL 

CREATE TABLE Orders ( OrderID int NOT NULL, OrderNumber int NOT NULL, PersonID int, PRIMARY KEY (OrderID), FOREIGN KEY (PersonID) REFERENCES Persons(PersonID) );

SQL Server / Oracle / MS Access:

CREATE TABLE Orders ( OrderID int NOT NULL PRIMARY KEY, OrderNumber int NOT NULL, PersonID int FOREIGN KEY REFERENCES Persons(PersonID) );

How to use Foreign key in SQL on multiple Column

CREATE TABLE Orders ( OrderID int NOT NULL, OrderNumber int NOT NULL, PersonID int, PRIMARY KEY (OrderID), CONSTRAINT FK_PersonOrder FOREIGN KEY (PersonID) REFERENCES Persons(PersonID) );

SQL FOREIGN KEY on ALTER TABLE

MySQL / SQL Server / Oracle / MS Access:

ALTER TABLE Orders ADD FOREIGN KEY (PersonID) REFERENCES Persons(PersonID);

DROP - FOREIGN KEY Constraint
How to drop foreign key constraints in SQL?

MySQL:
ALTER TABLE Orders DROP FOREIGN KEY FK_PersonOrder;

SQL Server / Oracle / MS Access:

ALTER TABLE Orders DROP CONSTRAINT FK_PersonOrder;


Hope!!! The above tutorial on " SQL FOREIGN KEY Constraint With Example" is helpful for you ...

Team,
QA acharya

Post a Comment

0 Comments