×

How to Add Foreign Key in SQL?

How to Add Foreign Key in SQL

Foreign key is an attribute or a set of attributes that references to primary key of same table or another table (relation).

  • Foreign key creation along with table creation

A foreign key can be created even at the time of creating tables.

Syntax:

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

Example:

Firstly, we will create a database with name “employeedb”. Then in that database we will create two tables “employee” and “department”. We will consider these tables and database for all the subsequent examples.

We will create a primary key and foreign key while creating the “employee” and “department” tables respectively.

mysql> USE employeedb;
 Database changed
 mysql> CREATE TABLE employee(Emp_ID INT NOT NULL PRIMARY KEY, Emp_Name VARCHAR(40), Emp_Salary VARCHAR(40));
 Query OK, 0 rows affected (0.07 sec)
 mysql> DESC employee;
 +------------+-------------+------+-----+---------+-------+
 | Field      | Type        | Null | Key | Default | Extra |
 +------------+-------------+------+-----+---------+-------+
 | Emp_ID     | int(11)     | NO   | PRI | NULL    |       |
 | Emp_Name   | varchar(40) | YES  |     | NULL    |       |
 | Emp_Salary | varchar(40) | YES  |     | NULL    |       |
 +------------+-------------+------+-----+---------+-------+
 3 rows in set (0.09 sec)
 mysql> CREATE TABLE department(Dept_ID INT NOT NULL PRIMARY KEY, Dept_Name VARCHAR(40), Emp_ID INT NOT NULL, FOREIGN KEY(Emp_ID) REFERENCES employee(Emp_ID));
 Query OK, 0 rows affected (0.20 sec)
 mysql> DESC department;
 +-----------+-------------+------+-----+---------+-------+
 | Field     | Type        | Null | Key | Default | Extra |
 +-----------+-------------+------+-----+---------+-------+
 | Dept_ID   | int(11)     | NO   | PRI | NULL    |       |
 | Dept_Name | varchar(40) | YES  |     | NULL    |       |
 | Emp_ID    | int(11)     | NO   | MUL | NULL    |       |
 +-----------+-------------+------+-----+---------+-------+
 3 rows in set (0.02 sec) 
Add Foreign Key in SQL

We have created two primary keys “Emp_ID” to an “employee” table, “Dept_ID” to “department” table and “Emp_ID” as a foreign key to “department” table while creating tables. To verify whether the keys are added to tables or not, we have used DESC command.

  • Foreign key creation with constraint name

A foreign key can be created even at the time of creating tables along with the constraint name. This constraint name will be useful while dropping a foreign key from a table without dropping an entire table.

Syntax:

CREATE TABLE tablename(ColumnName1 Datatype(SIZE) PRIMARY KEY, ColumnNameN Datatype(SIZE), CONSTRAINT ConstraintName FOREIGN KEY( ColumnName ) REFERENCES PARENT_TABLE_NAME(Primary_Key_ColumnName));

Example:

We will create a primary key and foreign key while creating the “employee” and “department” tables respectively. Foreign key will be created along with the foreign key constraint while creating the table itself.

 mysql> USE employeedb;
 Database changed
 mysql> CREATE TABLE employee(Emp_ID INT NOT NULL PRIMARY KEY, Emp_Name VARCHAR(40), Emp_Salary VARCHAR(40));
 Query OK, 0 rows affected (0.11 sec)
 mysql> DESC employee;
 +------------+-------------+------+-----+---------+-------+
 | Field      | Type        | Null | Key | Default | Extra |
 +------------+-------------+------+-----+---------+-------+
 | Emp_ID     | int(11)     | NO   | PRI | NULL    |       |
 | Emp_Name   | varchar(40) | YES  |     | NULL    |       |
 | Emp_Salary | varchar(40) | YES  |     | NULL    |       |
 +------------+-------------+------+-----+---------+-------+
 3 rows in set (0.01 sec)
 mysql> CREATE TABLE department(Dept_ID INT NOT NULL PRIMARY KEY, Dept_Name VARCHAR(40), Emp_ID INT NOT NULL, CONSTRAINT emp_id_fk FOREIGN KEY(Emp_ID) REFERENCES employee(Emp_ID));
 Query OK, 0 rows affected (0.25 sec)
 mysql> DESC department;
 +-----------+-------------+------+-----+---------+-------+
 | Field     | Type        | Null | Key | Default | Extra |
 +-----------+-------------+------+-----+---------+-------+
 | Dept_ID   | int(11)     | NO   | PRI | NULL    |       |
 | Dept_Name | varchar(40) | YES  |     | NULL    |       |
 | Emp_ID    | int(11)     | NO   | MUL | NULL    |       |
 +-----------+-------------+------+-----+---------+-------+
 3 rows in set (0.04 sec) 
Add Foreign Key in SQL

We have created two primary keys “Emp_ID” to an “employee” table, “Dept_ID” to “department” table and “Emp_ID” as a foreign key to “department” table while creating tables.  Here, we have also added foreign key constraint named as “emp_id_fk”. To verify whether the keys are added to tables or not, we have used DESC command.

  • Foreign key creation using ALTER command

It is possible to create a foreign key even after table creation. While creating a table if we have not added a foreign key to it and after that we need to add the foreign key to an existing table then we will use ALTER command in that case.

Syntax:

ALTER TABLE Parent_TableName ADD FOREIGN KEY(ColumnName) REFERENCES Child_TableName(ColumnName);

Example:

We will add a foreign key to an existing table using ALTER command.

 mysql> USE employeedb;
 Database changed
 mysql> CREATE TABLE employee(Emp_ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT, Emp_Name VARCHAR(40), Emp_Salary VARCHAR(40));
 Query OK, 0 rows affected (0.16 sec)
 mysql> DESC employee;
 +------------+-------------+------+-----+---------+----------------+
 | Field      | Type        | Null | Key | Default | Extra          |
 +------------+-------------+------+-----+---------+----------------+
 | Emp_ID     | int(11)     | NO   | PRI | NULL    | auto_increment |
 | Emp_Name   | varchar(40) | YES  |     | NULL    |                |
 | Emp_Salary | varchar(40) | YES  |     | NULL    |                |
 +------------+-------------+------+-----+---------+----------------+
 3 rows in set (0.01 sec)
 mysql> CREATE TABLE department(Dept_ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT, Dept_Name VARCHAR(40), Emp_ID INT NOT NULL);
 Query OK, 0 rows affected (0.12 sec)
 mysql> ALTER TABLE department ADD FOREIGN KEY(Emp_ID) REFERENCES employee(Emp_ID);
 Query OK, 0 rows affected (0.23 sec)
 Records: 0  Duplicates: 0  Warnings: 0
 mysql> DESC department;
 +-----------+-------------+------+-----+---------+----------------+
 | Field     | Type        | Null | Key | Default | Extra          |
 +-----------+-------------+------+-----+---------+----------------+
 | Dept_ID   | int(11)     | NO   | PRI | NULL    | auto_increment |
 | Dept_Name | varchar(40) | YES  |     | NULL    |                |
 | Emp_ID    | int(11)     | NO   | MUL | NULL    |                |
 +-----------+-------------+------+-----+---------+----------------+
 3 rows in set (0.01 sec) 
Add Foreign Key in SQL

We have created  two primary keys “Emp_ID” to an “employee” table and “Dept_ID” to “department” table while creating tables. Then using ALTER command we have added “Emp_ID” as foreign key to department table.  To verify whether the keys are added to tables or not, we have used DESC command.


Related Topics

SQL IN vs SQL EXISTS

SQL IN vs SQL EXISTS This article discusses in detail about the IN and the EXISTS operators in SQL. It is a common question between developers that what is the difference...

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

SQL Data Manipulation Language

Data Manipulation Language manipulates/make changes in data present in a table. It only affects data/records of table, not on the schema/structure of table. INSERT, UPDATE, DELETE are the commands of DML. INSERT: Stores...

2 minutes read.

SQL KEYS

SQL KEYS are single or multiple attributes used to get data from the table according to the requirement or condition. They can also be used to set up relationships amongst...

3 minutes read.

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 Top Clause

Top Clause: It returns the first ‘n’ number of rows as output. This Top clause is used to retrieve the required number of rows when there are thousands of records stored...

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

How to drop a column in SQL?

How to drop a column in SQL Introduction To delete a column from an already created table, one needs to use the ALTER command along with the DROP COLUMN clause. Syntax: ALTER TABLE tablename...

4 minutes read.

SQL Between Operator

SQL Between operator is a logical operator in the Structured Query Language. The Between operator is used to retrieve data within the range specified in the condition in the query. The...

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.

SQL SELECT SUM

The SQL Sum() function is an aggregate function in SQL that returns the total values of an expression. The expression may be numerical, or it may be an expression. Syntax: SELECT SUM(columnname)...

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 DROP Table

In this tutorial, we will help you to understand how to delete the table from the database in SQL with the help of examples. The DROP TABLE query is used to...

4 minutes read.

How to use LIKE in SQL

In this SQL article, we will learn and understand how to use LIKE to the columns in the SQL tables. What is Like? Like is an operator in the SQL. It is...

7 minutes read.

SQL Topological Sorting

It is for Directed Acyclic Graph, which linearly describes the ordering of graphs. It is not possible for all graphs, it is possible for only Directed acyclic graphs. Applications of Topological...

3 minutes read.

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

4 minutes read.

space() function in SQL

 This function returns a string with a specified number of spaces. If we specify a number, it returns the strings having that specified number of spaces. SPACE Function is available...

2 minutes read.

How to use INNER JOIN in SQL

In this article, we will learn about the INNER JOIN concept and how to use it in SQL with the WHERE clause. What is INNER JOIN in SQL? Inner Join is a...

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