SQL Foreign Key

HTML
CSS
C#
SQL

SQL Foreign Key

The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables. A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY KEY in another table. The table with the foreign key is called the child table, and the table with the primary key is called the referenced or parent table.

Look at the following two tables:

Notice that the “PersonID” column in the “Orders” table points to the “PersonID” column in the “Persons” table.

– The “PersonID” column in the “Persons” table is the PRIMARY KEY in the “Persons” table.
– The “PersonID” column in the “Orders” table is a FOREIGN KEY in the “Orders” table.
– The FOREIGN KEY constraint prevents invalid data from being inserted into the foreign key column, because it has to be one of the values contained in the parent table

Example:

CREATE TABLE tablename(ColumnName1 Datatype(SIZE) PRIMARY KEY, ColumnNameN Datatype(SIZE) FOREIGN KEY REFERENCES PARENT_TABLE_NAME(Primary_Key_Of_Parent_tbl));

The following SQL creates a FOREIGN KEY on the “PersonID” column when the “Orders” table is created:

CREATE TABLE Orders (

    OrderID int  PRIMARY KEY,

    OrderNumber int ,

    PersonID int FOREIGN KEY REFERENCES Persons(PersonID)

);

To allow naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple columns, use the following SQL syntax:

CREATE TABLE Orders (

    OrderID int ,

    OrderNumber int ,

    PersonID int,

    PRIMARY KEY (OrderID),

    CONSTRAINT FK_PersonOrder FOREIGN KEY (PersonID)

    REFERENCES Persons(PersonID)

);

To create a FOREIGN KEY constraint on the “PersonID” column when the “Orders” table is already created, use the following SQL:

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

To allow the naming of a FOREIGN KEY constraint, and for defining a FOREIGN KEY constraint on multiple columns, use the following SQL syntax:

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

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

ALTER TABLE Orders DROP CONSTRAINT FK_PersonOrder;

Course Video

1.Create two table in 1st table set primary key and insert 10 records and in 2nd table set FOREIGN key and insert 5 records in it.

2.Create two tables the second table should have a foreign key referencing the first table. Also, insert sample data into both tables

3.Create table without foreign key and add foreign key using alter table 

Hint: A foreign key constraint is added to the Budget table referencing the customer id column in the Customer table.

4.Create table with constrain primary key foreign key and unique key

Hint: A unique constraint is placed on the order id. A foreign key constraint is added to ensure referential integrity between the Orders table and the Customers table.1

5.write sql query to drop foreign key constrain