Create SQL Table with Foreign Key Constraint


This example shows how to create an SQL table with a FOREIGN KEY.

Below is a Student table with 5 students


Create a new Student_Address table with the FOREIGN KEY Student_ID.

CREATE TABLE Student_Address (
   ID INT NOT NULL,
   Street_Address VARCHAR(100) NOT NULL,
   Address_2 VARCHAR(10),
   City VARCHAR(100) NOT NULL,
   State VARCHAR(50) NOT NULL,
   Zip_Code VARCHAR(10) NOT NULL,
   PRIMARY KEY (ID),
   FOREIGN KEY (Student_ID) REFERENCES Student(ID)
);

The code above creates a Student_Address table with a Foreign Key Constraint Student_ID that refers to the ID column in the Student table.


Now take a look at the Student_Address table

All of the values of the Student_ID column must reference a valid ID in the Student table.


Please subscribe for more SQL and Programming examples.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s