×

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

SQL SELECT IN

SQL SELECT IN is a logical operator in Structured Query Language. It is used in SQL queries to reduce the use of multiple 'OR' operators. s The IN operator in SQL...

6 minutes read.

SQL WHERE Statement

SQL WHERE Statement Introduction WHERE clause is used to include a condition while fetching data from tables.When you have to specify a condition that has to be obeyed while data is...

9 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 TABLE

SQL TABLE Structured Query Language (SQL) is a relational database (RDBMS) where data is stored in the form of tables, that is, in rows and columns. These tables are known as...

3 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.

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.

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.

Pattern Matching in SQL

The LIKE in the Structured Query Language is a Logical Operator. The SQL LIKE is used within the WHERE clause in the SQL. This Like Operator is used with the...

5 minutes read.

SQL CREATE TABLE

In SQL tutorial, we learned and created different databases. To stores data in databases, we need to create a table. To create the table, we need to use CREATE TABLE...

5 minutes read.

SQL Cast Operator

While writing SQL queries, we can see many values which are to be converted into another datatype for accessing them. In SQL this conversion is generally done by CAST function. CAST...

4 minutes read.

SQL SELECT OR Operator

This SQL tutorial explains and helps us understand how to use the OR operator in the SELECT query with examples. The OR operator in the Structured Query Language is used to...

3 minutes read.

DELETE VS DROP in SQL

This page contains all the information about the Delete command and Drop command concept and the difference between the DELETE and DROP commands in SQL. What is the DELETE command in...

3 minutes read.

SQL Tutorial for Beginners

SQL tutorial provides basic and advanced concepts of Structured Query Language and how you deploy SQL to work with a relational database system. Our SQL tutorial is designed for beginners...

3 minutes read.

SQL COPY Table

In this tutorial, we will learn how to copy tables in SQL with the help of examples. Using the SELECT INTO statement in the SQL we can copy one table into...

4 minutes read.

SQL INTERSECT

SQL intersect operator is used to combine two or more SELECT statements, but it only displays the data similar to the SELECT statement. The syntax for the INTERSECT operation: SELECT COLUMN_NAME1, COLUMN_NAME2,...

3 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.

SQL Syntax

In this tutorial, we will help you understand about the different SQL Syntax concepts with the help of an example. Every Structured Query Language starts with Keywords like select, insert, update,...

5 minutes read.

Grant Command in SQL

What is DCL (Data Control Language)? Data Control Language (DCL) is a computer programming language with syntax intended to manage access to data kept in databases. It is a part of...

3 minutes read.

Drop vs Truncate in SQL

In this article, we will learn and understand the Drop and Truncate commands and the difference between these two commands. What is Drop Command? Drop is a Data Definition Language command in...

6 minutes read.

SQL INSERT INTO SELECT

In this tutorial, we will help you to understand and learn how to copy records from one table and add them to another table in the SQL with the help...

5 minutes read.