Computer >> Computer tutorials >  >> Programming >> MySQL

MySQL Syntax to create Foreign Key?


The syntax to create a foreign key is as follows −

alter table yourSecondTableName ADD CONSTRAINT yourConstraintname FOREIGN KEY(yourForeignKeyColumnName)
references yourFirstTableName (yourPrimaryKeyColumnName);

To understand the above syntax, let us create two tables. The query to create the first table is as follows −

mysql> create table Department_Table
   -> (
   -> Department_Id int not null auto_increment primary key,
   -> Department_Name varchar(30)
   -> );
Query OK, 0 rows affected (0.83 sec)

The query to create the second table is as follows −

mysql> create table Employee_Table
   -> (
   -> EmployeeID int not null auto_increment primary key,
   -> EmployeeName varchar(80),
   -> Job varchar(30),
   -> Department_Id int not null references department(departmentID)
   -> );
Query OK, 0 rows affected (1.12 sec)

The above Department_Id int, not null references department(departmentID) does not create a foreign key. Now follow the above syntax to create a foreign key.

The query is as follows −

mysql> alter table Employee_Table ADD CONSTRAINT fk_Department_Id FOREIGN KEY(Department_Id)
   -> references Department_Table(Department_Id);
Query OK, 0 rows affected (2.82 sec)
Records: 0 Duplicates: 0 Warnings: