×

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 ORDER BY

SQL ORDER BY The SQL ORDER BY clause is used to sort the data stored in tables in the database. The sorting can be done in an ascending way, descending way,...

5 minutes read.

SQL DROP Database

This tutorial will help us understand how to drop a database from the SQL Server with a few examples. The DROP command removes all the objects stored in the database and...

4 minutes read.

SQL GROUP BY CLAUSE

The GROUP BY clause is used to arrange similar records into the groups in the Structured Query Language queries. The records are arranged with the help of functions which is...

4 minutes read.

WEB SQL

What is Web SQL? In SQL we can create databases, read the data in the databases, insert the records into the databases, and delete the records from the databases. For storing...

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

GROUP BY vs ORDER BY

The GROUP BY clause and ORDER BY clause in SQL are used to arrange data obtained by SQL queries. The important difference between the GROUP BY clause and ORDER BY...

4 minutes read.

SQL Truncate

This command deletes all records from table. Truncate is a DDL command. Syntax: TRUNCATE table table_name; Example: Truncate table teacher; ORDER BY The ORDER BY clause arranges the table or column in ascending...

5 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 Operators

Arithmetic Operators Arithmetic operators are +, -, *, /, % performs addition, subtraction, multiplication, division, modulo respectively. Example:   Select 100+222; Select salary+100 From teacher Where teacher_id=1; Following output screen shows different arithmetic operations. We...

2 minutes read.

SQL Primary Key

A field, which contains unique data in a table, is called a PRIMARY KEY (PK). It means, a PRIMARY KEY field must contain unique data in the table. A PRIMARY KEY...

4 minutes read.

SQL Scalar Functions

TEACHER Table LCASE() Function The LCASE() function is used to return lower case values of specified column. Syntax: Select Lcase(column_name) from table_name; Example: Select Lcase(teacher_name) from teacher; Syntax: Select Lcase(column_name) from table_name [where condition]; Example: Select Lcase(teacher_name) from teacher where teacher_id=1; UCASE() Function The UCASE()...

1 minute read.

SQL Arithmetic Operators

This page contains all the information, learn about SQL Arithmetic Operators concept in the SQL table with the help of examples. The Arithmetic Operators is used to perform mathematical calculations on...

5 minutes read.

SQL Inner Join

In Structured Query Language, the most used join query is the Inner join query. Inner join query retrieves the records from one or more tables with similar data or records. The...

4 minutes read.

SQL SubQuery

The Sub-query in the SQL is the inner query placed or positioned inside another query, which is also known is the outer query. The inner query is embedded in the...

6 minutes read.

SQL SELECT AVG

In this tutorial, we will learn about the aggregate function name avg() function concept in SQL with the help of examples. The AVG() function is one of the aggregate functions in...

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

How to delete a row in SQL

Introduction To delete or remove the unused/unwanted rows from a table, DELETE command is used in SQL.DELETE command removes the entire record from a table.The DELETE statement can delete one or...

6 minutes read.

SQL FULL JOIN

In this section, we will help you understand the concept of the SQL FULL Join clause with a few examples. The SQL FULL Join query is executed to display the integrated...

3 minutes read.

Commit and Rollback in SQL

In Structured Query Language, we have Data Definition Language (DDL) and Data Manipulation Language (DML) commands the same way we have Transaction Control Language (TCL) commands in the Structured Query...

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.