×

SQL FOREIGN KEY

In this article, we will learn about the FOREIGN KEY constraints and how to define a FOREIGN KEY constraint to build the relationship between two tables.

In a Relational Databases Management System (RDBMS), a FOREIGN KEY is a field or bunch of fields which is used to build a relationship between two tables or join the two tables.

  • FOREIGN KEY is also known as referencing key in the RDBMS
  • Using FOREIGN KEY constraints between two tables, we define a parent-child relationship between two tables.
  • The field defines the PRIMARY KEY constraints in a table known as the parent table, while the same field defines the FOREIGN KEY constraints in another table is known as the child table.
  • There can be only one PRIMARY KEY in the table, but there is no defined limit on the FOREIGN KEY. We can have one or more than one FOREIGN KEY on the table.
  • We can define FOREIGN KEY constraints while creating the table or define FOREIGN KEY constraints on the already existing table.

Let’s take an example to understand and learn about the FOREIGN KEY constraints.

Example:

Here, we have two tables one is the Course table and the second is the Student table:

The students select courses. The following FOREIGN KEY constraints example is defined on one field.

Table Number One: Student Table

Student_IdFirst_NameLast_NameEmail_IdCity
101KareenaSayyedksayyed01@gmail.comHyderabad
102AnmolTemanianmolt23@gmail.comJalgaon
103HarshalPatelpatel02h@gmail.comMumbai
104SakshiHoodsakshihood10@gmail.comPune
105SureshKohlikohlisuresh1@gmail.comHyderabad

Table Number Two: Course Table

Course_IdCourse_NameStudent_Id
C101Java101
C102SQL102
C103SOANull
C104SAP104
C105MuleSoft103
C101Java105

In the Student table, the Student_Id field is the PRIMARY KEY and in the Course table, Student_Id is the FOREIGN KEY.

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.

Define FOREIGN KEY Constraints on CREATE TABLE

The following example defines a FOREIGN KEY on the Course table.

First, we have created the Student table with the following fields:

CREATE TABLE Student( Student_Id int NOT NULL, First_Name varchar(40) NOT NULL, Last_Name varchar(40) NOT NULL, Email_Id varchar(50),  City varchar(20) NOT NULL, PRIMARY KEY(Student_Id));

The following example shows how to define the FOREIGN KEY constraints on the other table.

Table Name Course:     

CREATE TABLE Course( Course_Id int NOT NULL, Course_Name varchar(40) NOT NULL, Student_Id int, FOREIGN KEY(Student_Id) REFERENCES Student(Student_Id));

In the Course table, we didn’t define any PRIMARY KEY. Just define the FOREIGN KEY constraints on the Student_Id.

The following FOREIGN KEY constraints example is defined on multiple fields.

Suppose we have three tables, one is the Package table, the second is the Data table, and the third is the Talk_time table:

Table 1: Package:

Package_IdData_IdTalktime_Id
P1001D1003T1001
P1002D1001T1002
P1003D1002T1003
P1004D1003T1004
P1005D1004T1005

Table 2: Data:

Data_IdData_LimitData_Price
D10015120
D1002375
D10036150
D100410240
D100515320

Table 3: Talk_Time:

Talk_Time_IdTalk_Time _LimitTalk_Time _Price
T1001120130
T100270105
T10036090
T1004200220
T1005150170

In the Talk_Time table, Talk_Time_Id is the PRIMARY KEY.

In the Data table, Data_Id is the PRIMARY KEY.

Whereas in the Package table, Talk_Time_Id and Data_Id are the FOREIGN keys

Table Number one: Data:

CREATE TABLE Data(Data_Id varchar(5) NOT NULL, Data_Limit int, Data_Price int, PRIMARY KEY(Data_Id));

Table Number two: Talk_Time:

CREATE TABLE Talk_Time(Talk_Time_Id varchar(5) NOT NULL, Talk_Time_Limit int, Talk_Time_Price int , PRIMARY KEY(Talk_Time_Id));

Table Number three: Package:

CREATE TABLE Package(Package_Id varchar(5) NOT NULL, Data_Id varchar(5), Talk_Time_Id varchar(5), FOREIGN KEY(Data_Id) REFERENCES Data(Data_Id), FOREIGN KEY(Talk_Time_Id) REFERENCES Talk_Time(Talk_Time_Id));

FOREIGN KEY Constraints using ALTER TABLE:

Suppose we have already created the table and want to define the FOREIGN KEY constraints on the field. We will use the ALTER TABLE query to add FOREIGN KEY constraints in such a case.

The follow query is used to add FOREIGN KEY constraints on the Student_Id field.

ALTER TABLE Course ADD FOREIGN KEY(Student_Id) REFERENCES Student(Student_Id);

ADD Keyword is used after the table name to add the FOREIGN KEY constraints to the already existing table.

DROP FOREIGN KEY constraint from the table

Use the following query to remove the FOREIGN KEY constraint from the table.

ALTER TABLE Course DROP FOREIGN KEY course_ibfk_1;

Drop keyword is used to remove FOREIGN KEY constraints from the Student_Id field.

course_ibfk_1 is the foreign key constraint name.

We can have null values in the FOREIGN KEY constraints field. We can have duplicate values in the FOREIGN KEY constraints field.


Related Topics

DDL Commands in SQL

DDL stands for Data Definition Language. Data Definition Language is a bunch of SQL commands used to create, modify and delete Database schema but not the records or data. Data Definition...

5 minutes read.

SQL Right Join

The SQL Right Join query displays all the table records and similar records from the left table. The query display zero records if it doesn’t find any similar records. If...

4 minutes read.

How to Create Temporary Table in SQL?

How to Create Temporary Table in SQL  Introduction to Temporary Tables Temporary table is a table which is used to store temporary data that can be used further in the same client...

3 minutes read.

SQL Queries

In a database, queries are used to request the result set of data from the table or action on the records. A Query can answer your simple or complicated question, perform...

5 minutes read.

SQL INSERT INTO Values

This article will help you in getting a better understanding of a very important SQL INSERT INTO VALUES function. INSERT INTO statement is used to insert or add a new record...

4 minutes read.

SQL SELECT Statement

The SQL SELECT statement is used to retrieve the data from the tables. We can also retrieve the selected records from the table using the query condition. The SQL SELECT...

5 minutes read.

SQL SELECT MIN

The SQL Min() function is an aggregate function in SQL. SQL Min() returns the minimum value of a given condition. The expression may be numerical, or it may be an expression. The syntax...

5 minutes read.

Nth highest salary

The most common and important question asked in interviews that how we can find the Nth highest salary in a table (2nd highest salary, 3rd highest salary, or Nth highest...

6 minutes read.

What is SQL Injection?

Introduction to SQL Injection SQL injection is a vulnerability or a technique that might destroy the database of a website or a web application. It is one of the most widely...

4 minutes read.

SQL CRUD Operation

In any computer language, CRUD operation is a foundation. CRUD operation rules are applied in databases as well. These operations are the basic operations used to perform with any database...

7 minutes read.

SQL Insert multiple rows

This article will deal with a new insertion method in SQL which inserts multiple rows at a time. Multiple records can be inserted at a time into a specific table with...

4 minutes read.

How to Update Table in SQL?

How to Update Table in SQL Introduction UPDATE query is used to update a record in a table. UPDATE is a DML command, which operates on the data of the table and not...

4 minutes read.

How to delete column in table

Introduction In SQL, sometimes it is required to delete a column of a table.The use of ALTER TABLE command with DROP COLUMN clause will serve the purpose to delete/remove a column...

4 minutes read.

SQL Count

Structured Query Language Count() Function is used with Structured Query Language SELECT Statement. SQL Count() function returns the number of items that match the specified criteria in the SELECT statement. Count()...

2 minutes read.

SQL UPDATE

SQL UPDATE The SQL UPDATE statement is utilized to update and modify the records present into a database. It is used to change the already existing records stored in the tables...

3 minutes read.

How to create a database in SQL?

How to create a database in SQL It is very necessary to create a database in order to store the data into the database.Database name must always be unique.SQL does not...

6 minutes read.

SQL Aggregate Functions

In this tutorial, we will learn and understand the SQL Aggregate Functions concept with the help of examples. SQL Aggregate Function is a function used to perform calculation operations on one...

4 minutes read.

SQL Select Distinct

The SQL DISTINCT query is used to fetch unique values from the tables using the SELECT statement in the SQL. There may be a situation that arises when you want to...

4 minutes read.

How to add column in table in SQL ?

How to add column in table in SQL  Introduction To add a column in already created table, one needs to use the ALTER command along with the ADD clause.If in the query,...

7 minutes read.

SQL VIEW

The SQL VIEW concept helps to hide the difficulty of the records and provides limitations to access to the database. The SQL view is similar to the SQL tables. In SQL...

7 minutes read.