
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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:
- Related Questions & Answers
- How to identify foreign key in MySQL DB?
- Foreign Key in RDBMS
- Correct MySQL INSERT ... ON DUPLICATE KEY syntax?
- Get a list of Foreign Key constraints in MySQL
- Verify that MySQL SET FOREIGN KEY CHECKS is set to = 1?
- sp_help for MySQL to display field types and foreign key constraints?
- How to refer primary key as Foreign to various table in MySQL?
- Difference between Primary key and Foreign key in Database
- Difference Between Primary key and Foreign key in DBMS
- Difference between Primary key and Foreign key in SQL Database
- Foreign key referencing of two DB2 tables
- Create MySQL column with Key=MUL?
- MySQL CREATE statement with KEY keyword
- How to disable MySQL foreign key checks and what are the benefits of disabling it?
- How to use Primary Key Constraints and Foreign Key Constraints to enforce database integrity in Oracle?
Advertisements